在Java中定向DFS

时间:2014-10-16 12:38:07

标签: java arrays algorithm recursion depth-first-search

我在让我的DFS正常工作时遇到问题。 图表的连接方式如下:

0 --> 1
0 --> 5
5 --> 4
4 --> 3
4 --> 2
2 --> 3
2 --> 0
3 --> 2
3 --> 5

所以我通过DFS运行后的结果应该是:

0,1,5,4,2,3

但我正在

0,1,5,2,3,4

继承人代码:

package kth.id2010.lab.lab05;

public class DFS {

    static void dfs(int edges[][], int vertex, boolean[] visited){        
        visited[vertex] = true;
        for(int i = vertex + 1; i < edges[vertex].length; i++){
            if(edges[vertex][i] == 1 && !visited[i]){
                dfs(edges,i,visited);
            }
        }
    }

    public static void main(String[] args){
        int n = 6;
        int[][] edges = new int[n][n];
        boolean[] visited = new boolean[n];
        //Vertex nr: 0
        edges[0][0] = 0;
        edges[0][1] = 1; //0 --> 1
        edges[0][2] = 0;
        edges[0][3] = 0;
        edges[0][4] = 0;
        edges[0][5] = 1; //0 --> 5
        //Vertex nr: 1
        edges[1][0] = 0;
        edges[1][1] = 0;
        edges[1][2] = 0;
        edges[1][3] = 0;
        edges[1][4] = 0;
        edges[1][5] = 0;
        //Vertex nr: 2
        edges[2][0] = 1; //2 --> 0
        edges[2][1] = 0;
        edges[2][2] = 0;
        edges[2][3] = 1; //2 --> 3
        edges[2][4] = 0;
        edges[2][5] = 0;
        //Vertex nr: 3
        edges[3][0] = 0;
        edges[3][1] = 0;
        edges[3][2] = 1; //3 --> 2
        edges[3][3] = 0;
        edges[3][4] = 0;
        edges[3][5] = 1; //3 --> 5
        //Vertex nr: 4
        edges[4][0] = 0;
        edges[4][1] = 0;
        edges[4][2] = 1; //4 --> 2
        edges[4][3] = 1; //4 --> 3
        edges[4][4] = 0;
        edges[4][5] = 0;
        //Vertex nr: 5
        edges[5][0] = 0;
        edges[5][1] = 0;
        edges[5][2] = 0;
        edges[5][3] = 0;
        edges[5][4] = 1; //5 --> 4
        edges[5][5] = 0;
        for(int i = 0; i <n; i++){
            visited[i] = false;
        }
        for(int i = 0; i <n; i++){
            if(visited[i] == false){
                dfs(edges,i,visited);
            }
        } 
    }
}

我无法弄清楚为什么它会在3次之后停止工作。

1 个答案:

答案 0 :(得分:2)

我注意到的是你从i = vertex + i开始,因此在你到达顶点5之后它将返回到我们从顶点0进入的主方法,并继续使用顶点2而不是顶点4 。因此,请更改以下行:

static void dfs(int edges[][], int vertex, boolean[] visited){        
    visited[vertex] = true;
    for(int i = vertex + 1; i < edges[vertex].length; i++){
        ...

为:

    for(int i = 0; i < edges[vertex].length; i++){