# Depth First Traversal for a graph

1083人阅读 评论(0)

Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. Depth First Traversal of the following graph is 2, 0, 1, 3

See this post for all applications of Depth First Traversal.
Following is C++ implementation of simple Depth First Traversal. The implementation uses adjacency list representation of graphs. STL‘s list container is used to store lists of adjacent nodes.

#include <iostream>
#include <list>
using namespace std;

class Graph
{
private:
int v;
void DFSUtil(int v, bool visited[]);
public:
Graph(int v);//Construtor
void DFS( int v);//DFS traversal of the vertices reachable from v
};

Graph::Graph(int v)
{
this->v = v;
}

{
}

void Graph::DFSUtil(int v, bool visited[])
{
//Mark the current node as node visited and print it
visited[v] = true;
cout << v << " ";

//Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
{
if( !visited[*i])
{
DFSUtil(*i, visited);
}
}
}

void Graph::DFS(int v)
{
//Mark all the vertices as not visited
bool *visited = new bool[v];
for( int i = 0; i < v; i++)
visited[i] = false;
//Call the recrusive helper function to print DFS tracersal
DFSUtil(v, visited);
}

int main(int argc, char* argv[])
{
Graph g(4);

cout << "Following is Depth First Traversal( starting from vertex 2 )\n";
g.DFS(2);
return 0;
}


Output:
Followint is Depth First Traversal(starting from vertex 2)
2 0 1 3
Note that the above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex (example Disconnected graph). To do complete DFS traversal of such graphs, we must call DFSUtil() for every vertex. Also, before printing a vertex in DFSUtil(), we should check if it is already printed by some other call of DFSUtil(). Following implementation does the complete graph traversal even if the nodes are unreachable. The differences from the above code are highlighted in the below code.
class Graph
{
int V;    // No. of vertices
void DFSUtil(int v, bool visited[]);  // A function used by DFS
public:
Graph(int V);   // Constructor
void addEdge(int v, int w);   // function to add an edge to graph
void DFS();    // prints DFS traversal of the complete graph
};

Graph::Graph(int V)
{
this->V = V;
}

{
}

void Graph::DFSUtil(int v, bool visited[])
{
if(visited[v] == false)
{
// Mark the current node as visited and print it
visited[v] = true;
cout << v << " ";

// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
if(!visited[*i])
DFSUtil(*i, visited);
}
}

// The function to do DFS traversal. It uses recursive DFSUtil()
void Graph::DFS()
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;

// Call the recursive helper function to print DFS traversal
// starting from all vertices one by one
for(int i = 0; i < V; i++)
DFSUtil(i, visited);
}

Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.


1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：724035次
• 积分：7845
• 等级：
• 排名：第2750名
• 原创：133篇
• 转载：35篇
• 译文：7篇
• 评论：118条
声明
本博客乃学习笔记，没有纯粹无意义的转载。作者除了对自己负责，不对任何读者负责。欢迎指出文章错误，如果原意交朋友，可以通过Gmail联系我（mingxinglai#gmail.com），博客基本不再更新，欢迎访问我的独立博客http://mingxinglai.com
文章分类
评论排行
最新评论