c - 如何找到从一个节点开始的所有简单路径?

标签 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

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

最佳答案

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

因此,当您回溯时,您无法沿着某个节点遵循另一条路线。我建议你添加

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;
}

关于c - 如何找到从一个节点开始的所有简单路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442079/

相关文章:

Javascript:将多维数组展平为唯一路径数组

.net - 编译 C 以使用 CLR

c - 为什么我需要在独立应用程序中添加脚本引擎

C memcpy 导致段错误

javascript - (d3) 单轴、可缩放时间轴的动态合并?

r - 在美国 map 上绘制数值

algorithm - 查找树中的公共(public)子树

algorithm - graph - 如果我已经有并且只有父数组,如何打印两个顶点之间的路径?

c++ - 使用 Dev C++ 在 C++ 中使用 RapidXML 编译错误

c++ - 如何处理正则表达式?