1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| public class DFS { char[] vertex={'a','b','c','d','e','f','g','h','i','j'}; int n=10; int []visited=new int[n]; int edge[][]={ {0,1,0,0,0,1,1,0,0,0}, {1,0,1,1,1,0,0,0,0,0}, {0,1,0,0,0,0,0,0,0,0}, {0,1,0,0,1,0,0,0,0,0}, {0,1,0,1,0,0,0,0,0,0}, {1,0,0,0,0,0,1,0,0,0}, {1,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,1,1}, {0,0,0,0,0,0,0,1,0,1}, {0,0,0,0,0,0,0,1,1,0}, };
void init(){ for (int i=0;i<=n-1;i++) visited[i]=0; }
void DFSk (Graph g, int k) { visited[k]=1; System.out.print(vertex[k]+"已访问 "); for (int i=0;i<=n-1;i++) if (g.edge[k][i]==1 && visited[i]==0) DFSk(g,i); }
void DFSt (Graph g) { for (int i=0;i<=n-1;i++) { if (visited[i] == 0){ System.out.print("\n本次访问头:"+vertex[i]+" "); DFSk(g, i); } } }
public static void main(String[] args) { System.out.println("访问顺序:"); DFS dfs=new DFS(); dfs.DFSt(new Graph(dfs.vertex, dfs.edge)); }
}
class Graph { char []vertex; int edge[][];
public Graph(char[] vertex, int[][] edge) { this.vertex = vertex; this.edge = edge; } }
|