import java.util.Stack; import sun.misc.Queue; public class DFS { public static int graph [][] = { {1,2},//0 {0,3,4},//1 {0,5,6},//2 {1,7},//3 {1,7},//4 {2,7},//5 {2,7},//6 {3,4,5,6}//7 }; static Stack stack = new Stack(); static Queue outPut = new Queue(); static int visited [] = {-1,-1,-1,-1,-1,-1,-1,-1};//Initialize all unvisited. public static int [] findNeighbours(int v){ return graph[v]; } public static boolean isVisited(int v){ if(visited[v]==1){ return true; }else{ return false; } } public static void main(String[] args) throws InterruptedException{ stack.push(0); while(!stack.empty()){ int vertex = (Integer)stack.pop(); if(!isVisited(vertex)){ visited[vertex]=1; outPut.enqueue(vertex); int neighbours []= findNeighbours(vertex); for(int i = 0 ;i<neighbours.length;i++){ if(!isVisited(neighbours[i])){ stack.push(neighbours[i]); } } } } while(!outPut.isEmpty()){ System.out.print(outPut.dequeue()); } } }
BFS
沒有留言:
張貼留言