深度优先搜索Depth-first search (DFS) for undirected graphs

无向图的深度优先搜寻(DFS)。

Depth-first search, or DFS, 是一种遍历图的方法。它只是简单地访问图中的结点,但是上百种图算法都是基于DFS的。因此,学习图理论之前理解DFS就至关重要了。DFS算法规则很简单:从一个结点开始,尽可能往前“走”(按深度),“走不动了”就回溯。

Algorithm

在DFS中,结点有三种状态,用三种颜色代表。

白色代表未访问

;灰色代表正在访问

黑色代表访问结束

初始状态,节点都是白色(未访问)。 DFS 从任意结点u开始:

  1. Mark vertex u as gray (visited).
  2. For each edge (u, v), where v is white, run depth-first search forv recursively.
  3. Mark vertex u as black and backtrack to the parent.

下面举例:从1开始:

depth-first search example, pic. 1Source graph.
Mark a vertex 1 as gray.
There is an edge (1, 4) and a vertex 4 is unvisited. Go there.
Mark the vertex 4 as gray.
There is an edge (4, 2) and vertex a 2 is unvisited. Go there.
Mark the vertex 2 as gray.
There is an edge (2, 5) and a vertex 5 is unvisited. Go there.
Mark the vertex 5 as gray.
There is an edge (5, 3) and a vertex is unvisited. Go there.
Mark the vertex 3 as gray.
There are no ways to go from the vertex 3. Mark it as black and backtrack to the vertex 5.
There is an edge (5, 4), but the vertex 4 is gray.
There are no ways to go from the vertex 5. Mark it as black and backtrack to the vertex 2.
There are no more edges, adjacent to vertex 2. Mark it as black and backtrack to the vertex 4.
There is an edge (4, 5), but the vertex 5 is black.
There are no more edges, adjacent to the vertex 4. Mark it as black and backtrack to the vertex 1.
There are no more edges, adjacent to the vertex 1. Mark it as black. DFS is over.

从上面例子看出,DFS没有检查所有边。DFS所经过的点和边构成了一棵树。而这棵树就是DFS的递归树。

复杂度分析

假设图是连通图。DFS访问每个节点并且检查结点的每条边。因此,DFS的时间复杂度是O(V+E)。如果图是用邻接矩阵存储图的话,就不能有效找到节点的所有边,所以复杂度会变为O(V^2)。

代码C++

int vertexcount;//
enum VertexState
{
    white,
    gray,
    black
};

void Graph::runDFS(int u,VertexState* state)
{
    state[u]=gray;
    for(int v=0;i<vertexcount;v++)
        if(isEage(u,v))
        {
            runDFS(v,state);
        }
    state[u]=black;
}

vod Graph::DFS()
{
    VertexState* state=new VertexState[vertexcount];
    for(int i=0;i<vertexcout;i++)
        state[i]=white;
    runDFS(0,state);
    delete[] state;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值