【问题标题】:Depth First Search using Adjacency Matrix?使用邻接矩阵的深度优先搜索?
【发布时间】:2017-08-08 11:54:48
【问题描述】:

我正在尝试使用递归和二维数组在邻接矩阵上实现深度优先搜索并遇到问题。我还是新手,如果我的错误太明显了,请见谅。

如果所有数字都为 0 并且不显示访问的组件,我的代码不会读取该行。

例如一个 10x10 的矩阵,在行、列 (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); 调用它关于主要方法。 array 是二维矩阵。

标签: java recursion multidimensional-array depth-first-search adjacency-matrix


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多