Using adjacency table to store graphs
Input source point start after entering graph
Implementation of BFS stack with queue for DFS
1#include <cstdio>2#include <vector>3#include <cstring>4#include <queue>5#include <stack>6 using namespacestd;7 8 Const intmaxn=1e3+Ten;9 Ten intn,m; One A struct Picture - { - intNODE[MAXN]; thevector<int>EDGE[MAXN]; - voidAddedge (intAintb//Add a to B edge to the diagram - { - Edge[a].push_back (b); + } - }; + A at - voidBFS (Picture map,intStart//wide search traverse diagram - { -queue<int>Ans,ha; - intVIS[MAXN]; -memset (Vis,0,sizeof(Vis)); in Ha.push (start); - Ans.push (start); tovis[start]=1; + while(!ha.empty ())//Breadth Traversal - { the intPoint=Ha.front (); * Ha.pop (); $ for(intI=0; I<map.edge[point].size (); i++)Panax Notoginseng{//traverse each edge on a point - intx=Map.edge[point][i]; the if(!Vis[x]) + { A Ha.push (x); the Ans.push (x); +vis[x]=1; - } $ } $ } - while(!ans.empty ()) - { theprintf"%d", Ans.front ()); - Ans.pop ();Wuyi } theprintf"\ n"); - } Wu - voidDFS (Picture map,intStart//Depth Traversal diagram About { $queue<int>ans; -stack<int>haha; -vector<int>VIS[MAXN]; - for(intI=1; i<=n;i++)//initializing adjacency table Vis A { + int_size=map.edge[i].size (); the while(_size--) - { $Vis[i].push_back (0); the } the } the Haha.push (start); the Ans.push (start); - while(!haha.empty ())//Deep Search in { the intx=-1; the intPoint=haha.top (); About int_size=map.edge[point].size (); the for(intI=0; i<_size;i++)//Traverse each edge the { the inttmp=Map.edge[point][i]; + if(!vis[point][i])//if the edge of point I is not accessed - { thevis[point][i]=1;Bayix=tmp; the Ans.push (x); the Haha.push (x); - Break; - } the } the if(x==-1)//if all edges of point have been accessed the { the Haha.pop (); - } the } the while(!ans.empty ()) the {94printf"%d", Ans.front ()); the Ans.pop (); the } theprintf"\ n");98 } About - intMain ()101 {102 while(~SCANF ("%d%d", &n,&m))//Enter a graph of n points m edges103 {104 Picture map; the for(intI=0; i<m; i++)//adding M-Bars to the diagram106 {107 intb;108scanf"%d%d",&a,&b);109 Map.addedge (A, b); the }111 intstart; thescanf"%d", &start);//input source Point113printf"dfs:\n"); the DFS (Map,start); theprintf"bfs:\n"); the BFS (map,start);117 }118 return 0;119 } - /*121 122 7 6123 1 2124 1 3 the 2 4126 2 5127 3 6 - 3 7129 1 the 131 1 the 2 3133 4 5 6 7134 135 */
Non-recursive traversal of data structures with graphs