Depth-first traversal (DFS) C + + non-recursive implementation of graphs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.