如何找到一个节点的所有简单路径?

时间:2019-08-10 12:17:31

标签: c graph tree

我有一个这样的图形,现在我想从0打印所有路径

             0
             |
             1 
           /   \
          2 --- 3
          |    / \
          5---6---4

预期产量

All the path from 0 are:
0123465
0123645
0125634
0125643
0132564
0134652
01364
013652

我试图画一棵树来理解这个问题。

enter image description here

我已经尝试对其进行编程:

int main(){ 
        ...

        //print  all node
        // choose the start node as 0
        int startV = 0;
        // init the path
        int path = startV;
        // init the visited array; 
        int visited[7] = {-1, -1, -1, -1, -1, -1, -1};

        Recur(g, n, 0, path, visited);
}

void Recur(Graph g, int numV, Vertex startV, int path, int *visited) {
    // DFS recursive algorithm

    // mark this node as visited
    visited[startV] = 1;

    // travel all the nodes under startV, 
    for (int i = 0; i < numV; i++) {
        // if there is an edge between node startV and node i && node i haven't visited 
        if (isEdge(newEdge(startV, i), g) && visited[i] == -1) {
            // save and print the path
            path = path * 10 + i;
            printf("path:%d\n", path);
            // recursive: repeat this, i as the startV
            Recur(g, numV, i, path, visited);
        }
    }


}

但是,我的代码只能输出此内容。

path:1
path:12
path:123
path:1234
path:12346
path:123465

我认为我的访问列表和回溯方法可能存在一些问题。有人可以给我一些建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您尚未“取消访问”任何节点。

因此,当您回溯时,您将无法通过节点遵循另一条路线。我建议您添加

visited[startV] = -1;

Recur函数的结尾。

void Recur(Graph g, int numV, Vertex startV, int path, int *visited) {

    // mark this node as visited
    visited[startV] = 1;

    //...

    // mark this node as not visited
    visited[startV] = -1;
}