0
我想使用递归和二维数组来实现深度优先搜索的邻接矩阵和有问题。我仍然对此感到陌生,不好意思,如果我的错误太明显了。深度优先搜索使用邻接矩阵?
如果所有数字都是0并且不显示访问的组件,我的代码不会读取该行。
例如,10x10 martrix在行,列(9,6)和(6,9)上分别只有1个。其他的都是0
它应该输出
Component: 1
Component: 2
Component: 3
Component: 4
Component: 5
Component: 6 9
Component: 7
Component: 8
Component: 10
Total number of Components: 9
这是迄今为止我的方法。
public static void dfs(int i, int[][] G) {
boolean [] visited = new boolean[10];
if(!visited[i]){
visited[i] = true; // Mark node as "visited"
System.out.println("Compnent: ");
System.out.println(i+1 + " ");
for (int j = 0; j < G[i].length-1; j++) {
if (G[i][j]==1 && !visited[j]) {
dfs(j, G); // Visit node
}
}
}
}
只有上述显示是组件1,然后停止方法。
请告诉我你怎么称呼DFS方法? –
我用dfs(0,array)调用它;主要方法。数组是2d矩阵。 – JohnMurphy27