深度优先搜索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开始:

Source 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.
深度优先搜索Depth-first search (DFS) for undirected graphs_第1张图片 There is an edge (4, 2) and vertex a 2 is unvisited. Go there.
Mark the vertex 2 as gray.
深度优先搜索Depth-first search (DFS) for undirected graphs_第2张图片 There is an edge (2, 5) and a vertex 5 is unvisited. Go there.
深度优先搜索Depth-first search (DFS) for undirected graphs_第3张图片 Mark the vertex 5 as gray.
There is an edge (5, 3) and a vertex is unvisited. Go there.
深度优先搜索Depth-first search (DFS) for undirected graphs_第4张图片 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.
深度优先搜索Depth-first search (DFS) for undirected graphs_第5张图片 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;
}


你可能感兴趣的:(深度优先搜索Depth-first search (DFS) for undirected graphs)