// 图的深度优先搜索
public class DFSTest { public static void main(String[] args) { int[][] graph={ {0,1,1,0,0,0,0,0}, {1,0,0,1,1,0,0,0}, {1,0,0,0,0,1,1,0}, {0,1,0,0,0,0,0,1}, {0,1,0,0,0,0,0,1}, {0,0,1,0,0,0,1,0}, {0,0,1,0,0,1,0,0}, {0,0,0,1,1,0,0,0}, }; int[] list; DFS dfs=new DFS(); dfs.input(graph, 0); list=dfs.getList(); for(int i=0; i<graph.length; i++){ System.out.print(list[i]+" "); } } }
class DFS { int[][] graph; int[] list; int[] visited; int j; void input(int[][] graph, int v) { this.graph=graph; visited=new int[graph.length]; list=new int[graph.length]; for(int i: visited) i=0; j=0; calculate(v); } void calculate(int v) { visited[v]=1; list[j++]=v; for(int k=0; k<graph.length; k++){ if(graph[v][k]==1 && visited[k]==0){ calculate(k); } } } int[] getList() { return list; } }
|