The following is the teacher as a data structure class job requirements, there is no practical use and can be explored and summed up the place, so simple code directly display.
Width-First traversal:
1#include <cstdio>2#include <iostream>3#include <cstring>4 using namespacestd;5 6 #define_CLR (x, y) memset (x, y, sizeof (x))7 #defineN 10108 9 inthead[n], tot;Ten structEdge One { A intV, next; - }edge[n]; - intQueue[n]; the BOOLUsed[n]; - - voidADD (intUintv) - { +EDGE[TOT].V =v; -Edge[tot].next =Head[u]; +Head[u] = tot++; A } at - voidBFsints) - { -_CLR (Queue,0); -_CLR (Used,0); - intFront=0, rear=0; inqueue[rear++] =1; -cout << S <<" "; toUsed[s] =true; + while(Front <rear) - { the intCur = queue[front++]; * for(intI=head[cur]; i!=-1; I=edge[i].next) $ {Panax Notoginseng intv =edge[i].v; - if(!Used[v]) the { +USED[V] =true; Acout << v <<" "; thequeue[rear++] =v; + } - } $ } $cout <<Endl; - } - intMain () the { - intN, m, x, y;Wuyicout <<"Please enter the number of vertices and the number of sides of the graph:"; the while(Cin >> n >> m && n+m) - { Wutot =0; -_CLR (Head,-1); About for(intI=0; i<m; i++) $ { -scanf"%d%d", &x, &y); - Add (x, y); - } Acout <<"The breadth-first traversal sequence is as follows: \ n"; +BFs1); thecout<<Endl; -cout <<"Please enter the number of vertices and sides of the graph (enter two 0 for end input):"; $ } the return 0; the}
Depth-First traversal:
1#include <cstdio>2#include <iostream>3#include <cstring>4 using namespacestd;5 6 #define_CLR (x, y) memset (x, y, sizeof (x))7 #defineN 10108 9 inthead[n], tot;Ten structEdge One { A intV, next; - }edge[n]; - intQueue[n]; the BOOLUsed[n]; - - voidADD (intUintv) - { +EDGE[TOT].V =v; -Edge[tot].next =Head[u]; +Head[u] = tot++; A } at - voidDfsints) - { -cout << S <<" "; - for(intI=head[s]; i!=-1; I=edge[i].next) - { in intv =edge[i].v; - if(!Used[v]) to { +USED[V] =true; - Dfs (v); the } * } $ }Panax Notoginseng intMain () - { the intN, m, x, y; +cout <<"Please enter the number of vertices and the number of sides of the graph:"; A while(Cin >> n >> m && n+m) the { +tot =0; -_CLR (Head,-1); $ for(intI=0; i<m; i++) $ { -scanf"%d%d", &x, &y); - Add (x, y); the } -cout <<"The deep priority traversal sequence is as follows: \ n";WuyiDfs1); thecout<<Endl; -cout <<"Please enter the number of vertices and sides of the graph (enter two 0 for end input):"; Wu } - return 0; About}
The breadth and depth of graphs first traverse the C language