Non-recursive Version of DFS Algorithm

DFS is the most important graph traversal algorithm and has been adopted as the default traversal module for many software system. In this article, the non-recursive implementation of DFS in C++ is given. The basic idea is to record the vertexes during traversal by utilizing a stack, and decide whether a vertex need to be pushed into the stack according to a mark array which indicate whether the current vertex has been visited.

 

 void adjacent_matrix_graph::depth_first( int v ) const { bool * visited = new bool[n_vertex]; for( int i = 0; i < n_vertex; ++i ) visited[i] = false; stack<int> v_stack; for( int i = 0; i < n_vertex; ++i ) { v_stack.push( i ); while( ! v_stack.empty() ) { int v = v_stack.top(); if( !visited[v] ) { visited[v] = true; cout << v << " "; } int u = first_adj_vertex( v ); while( u != -1 && visited[u] ) u = next_adj_vertex( v, u ); if( u == -1 ) v_stack.pop(); else v_stack.push( u ); } cout << endl; } cout << endl; delete [] visited; }

你可能感兴趣的:(Non-recursive Version of DFS Algorithm)