图的广度、深度优先遍历 C语言
以下是老师作为数据结构课的作业的要求,没有什么实际用处和可以探讨和总结的的地方,所以简单代码直接展示。
宽度优先遍历:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 using namespace std; 5 6 #define _clr(x, y) memset(x, y, sizeof(x)) 7 #define N 1010 8 9 int head[N], tot; 10 struct Edge 11 { 12 int v, next; 13 }edge[N]; 14 int Queue[N]; 15 bool used[N]; 16 17 void Add(int u, int v) 18 { 19 edge[tot].v = v; 20 edge[tot].next = head[u]; 21 head[u] = tot++; 22 } 23 24 void bfs(int s) 25 { 26 _clr(Queue, 0); 27 _clr(used, 0); 28 int front=0, rear=0; 29 Queue[rear++] = 1; 30 cout << s <<" "; 31 used[s] = true; 32 while(front < rear) 33 { 34 int Cur = Queue[front++]; 35 for(int i=head[Cur]; i!=-1; i=edge[i].next) 36 { 37 int v = edge[i].v; 38 if(!used[v]) 39 { 40 used[v] = true; 41 cout << v << " "; 42 Queue[rear++] = v; 43 } 44 } 45 } 46 cout << endl; 47 } 48 int main() 49 { 50 int n, m, x, y; 51 cout << "请输入图的顶点数和边数: "; 52 while(cin >> n >> m && n+m) 53 { 54 tot = 0; 55 _clr(head, -1); 56 for(int i=0; i<m; i++) 57 { 58 scanf("%d%d",&x, &y); 59 Add(x, y); 60 } 61 cout << "广度优先遍历顺序如下:\n"; 62 bfs(1); 63 cout<<endl; 64 cout << "请输入图的顶点数和边数(输入两个0代表结束输入): "; 65 } 66 return 0; 67 }
深度优先遍历:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 using namespace std; 5 6 #define _clr(x, y) memset(x, y, sizeof(x)) 7 #define N 1010 8 9 int head[N], tot; 10 struct Edge 11 { 12 int v, next; 13 }edge[N]; 14 int Queue[N]; 15 bool used[N]; 16 17 void Add(int u, int v) 18 { 19 edge[tot].v = v; 20 edge[tot].next = head[u]; 21 head[u] = tot++; 22 } 23 24 void dfs(int s) 25 { 26 cout << s << " "; 27 for(int i=head[s]; i!=-1; i=edge[i].next) 28 { 29 int v = edge[i].v; 30 if(!used[v]) 31 { 32 used[v] = true; 33 dfs(v); 34 } 35 } 36 } 37 int main() 38 { 39 int n, m, x, y; 40 cout << "请输入图的顶点数和边数: "; 41 while(cin >> n >> m && n+m) 42 { 43 tot = 0; 44 _clr(head, -1); 45 for(int i=0; i<m; i++) 46 { 47 scanf("%d%d",&x, &y); 48 Add(x, y); 49 } 50 cout << "深优先遍历顺序如下:\n"; 51 dfs(1); 52 cout<<endl; 53 cout << "请输入图的顶点数和边数(输入两个0代表结束输入): "; 54 } 55 return 0; 56 }