The deep search algorithm is necessary for programmers, not only to be, but also to be skilled. In the ACM competition, Deep Search also holds a very important part. This paper uses explicit stack (non-recursive) to realize the depth-first traversal of graphs, hoping that we can learn from each other.
The basic idea of the stack implementation is to kick a node with all the inaccessible "Neighbors" (that is, "a layer of neighbor nodes") into the stack, and then attack on the top node, where each node is accessed and kicked out. Readers can draw their own analysis, the difficulty is not big. The code is written in a casual, reference-only. ~
#include <iostream>#include<stack>using namespacestd;#defineMaxnode 20#defineMAX 2000#defineStartnode 1intMap[maxnode+1][maxnode+1];voidDfs_stack (intStartintN) { intVisited[maxnode],s_top; for(inti =0; I <= Maxnode; i++) {Visited[i]=0; } Visited[start]=1; Stack<int>s; cout<<start<<" "; for(inti =1; I <= N; i++){ if(Map[i][start] = =1&&!Visited[i]) {Visited[i]=1; S.push (i); } } while(!S.empty ()) {S_top=S.top (); Visited[s_top]=1; cout<<s_top<<" "; S.pop (); for(inti =1; I <= N; i++){ if(Map[i][s_top] = =1&&!Visited[i]) {Visited[i]=1; S.push (i); } } } }intMainintargcConst Char*argv[]) { intNum_edge,num_node; intx, y; cout<<"Input number of nodes and edges >"<<Endl; CIN>>num_node>>Num_edge; for(inti =0; i<num_node;i++){ for(intj=0; j<num_node;j++) {Map[i][j]=0; } } for(inti =1; I <= Num_edge; i++) {cin>>x>>y; Map[x][y]= Map[y][x] =1; } dfs_stack (Startnode, Num_node); return 0;}
Graph's Depth-first traversal (DFS) C + + non-recursive implementation