Java 使用邻接矩阵进行深度优先搜索?

Java 使用邻接矩阵进行深度优先搜索?,java,recursion,multidimensional-array,depth-first-search,adjacency-matrix,Java,Recursion,Multidimensional Array,Depth First Search,Adjacency Matrix,我试图使用递归和2D数组来实现邻接矩阵的深度优先搜索,但遇到了一些问题。我还是个新手,如果我的错误太明显,我很抱歉 如果所有数字均为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 Co

我试图使用递归和2D数组来实现邻接矩阵的深度优先搜索,但遇到了一些问题。我还是个新手,如果我的错误太明显,我很抱歉

如果所有数字均为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,然后方法停止。

在您的示例中,第一个节点和其他节点之间没有连接。因此,我们不能离开第一个节点

代码应该是这样的:

public static void dfs(int i, int[][] graph, boolean[] visited) {
    if(!visited[i]){        
        visited[i] = true; // Mark node as "visited"
        System.out.print(i+1 + " ");

        for (int j = 0; j < graph[i].length; j++) {
            if (graph[i][j]==1 && !visited[j]) {   
                dfs(j, graph, visited); // Visit node
            }
        }
    }   
}

public static void main(String[] args) {
    // your matrix declare
    boolean [] visited = new boolean[10];
    int count = 0;
    for(int i = 0; i < graph.length; i++) {
        if(!visited[i]) {
            System.out.println("Compnent: " );
            dfs(i,graph,visited);
            ++count;
        }
    }
    System.out.println("Total number of Components: " + count);
}

请告诉我如何调用dfs方法?我使用dfs0数组调用它;关于主要方法。数组是二维矩阵。