像这样遍历有向图的算法(图片里面)

时间:2011-05-24 17:20:21

标签: graph traversal

我有一个这样的图表:

graph

一条简单的规则:
图中的每个节点只知道其后继者。

正如您所看到的,当我们来到6时(第一个分支1 → 6)出现问题,因此我们不知道何时停止并开始遍历另一个分支(2 → 6)。

有人建议使用这样的遍历图的算法吗?

当我遍历1 → 6 → end of graph,然后返回2 → 6时,我提出了这个想法。
但我认为这不是一个好主意,因为1 → 6 → end of graph方式可能有很多分叉。

3 个答案:

答案 0 :(得分:3)

从根本上说,traverse a graph只有两种方式。

  1. Depth-first search
  2. Breadth-first search
  3. 当然,还有很多其他选择,但这些选项最简单,最普遍适用。其他算法大多可以被认为是对这些主题的变化。选择最适合您的问题并前往城镇!

答案 1 :(得分:1)

递归地,当你穿过它时标记每个节点,当没有任何东西可以探索时你回去。

看起来像

的东西
function 

mark the current edge
for all it's vertices
call the function on the edge that is connected with the vertice if the edge is not marked
do something with the edge (display or whatever)
once there is no vertices left return 
例如,如果图形由相邻矩阵表示,则长度为1000表示没有顶点。

void inDepth(int i)
{
    int j;

    edges[i] = 1; //edges is the marking vector

    for (j=0; j<N; j++)
    {
        if ((vertices[i][j]<1000) && (vertices[i][j]>0) && (edges[j]==0)) 
        {
            inDepth(j); 
        }
    }

    printf("%d ",i);
}

答案 2 :(得分:0)

这不是DFS搜索吗? (Depth First Search