问题及代码:
测试用图如下:
![](https://img-blog.csdn.net/20161116202453022)
1、深度优先遍历---DFS
头文件graph.h和源文件graph.cpp代码详见第十二周项目1--图基本算法库
主函数main.cpp代码:
- <span style="font-size:12px;">#include "graph.h"
- int visited[MAXV];
- void DFS(ALGraph *G, int v)
- {
- ArcNode *p;
- int w;
- visited[v]=1;
- printf("%d ", v);
- p=G->adjlist[v].firstarc;
- while (p!=NULL)
- {
- w=p->adjvex;
- if (visited[w]==0)
- DFS(G,w);
- p=p->nextarc;
- }
- }
-
- int main()
- {
- int i;
- ALGraph *G;
- int A[5][5]=
- {
- {0,1,0,1,0},
- {1,0,1,0,0},
- {0,1,0,1,1},
- {1,0,1,0,1},
- {0,0,1,1,0}
- };
- ArrayToList(A[0], 5, G);
-
- for(i=0; i<MAXV; i++) visited[i]=0;
- printf(" 由2开始深度遍历:");
- DFS(G, 2);
- printf("\n");
-
- for(i=0; i<MAXV; i++) visited[i]=0;
- printf(" 由0开始深度遍历:");
- DFS(G, 0);
- printf("\n");
- return 0;
- }
- </span>
运算结果:
![](https://img-blog.csdn.net/20161124101959227?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
2、广度优先遍历---BFS
头文件graph.h和源文件graph.cpp代码详见第十二周项目1--图基本算法库
主函数main.cpp代码:
- <span style="font-size:12px;">#include "graph.h"
-
- void BFS(ALGraph *G, int v)
- {
- ArcNode *p;
- int w,i;
- int queue[MAXV],front=0,rear=0;
- int visited[MAXV];
- for (i=0; i<G->n; i++) visited[i]=0;
- printf("%2d",v);
- visited[v]=1;
- rear=(rear+1)%MAXV;
- queue[rear]=v;
- while (front!=rear)
- {
- front=(front+1)%MAXV;
- w=queue[front];
- p=G->adjlist[w].firstarc;
- while (p!=NULL)
- {
- if (visited[p->adjvex]==0)
- {
- printf("%2d",p->adjvex);
- visited[p->adjvex]=1;
- rear=(rear+1)%MAXV;
- queue[rear]=p->adjvex;
- }
- p=p->nextarc;
- }
- }
- printf("\n");
- }
-
-
- int main()
- {
- ALGraph *G;
- int A[5][5]=
- {
- {0,1,0,1,0},
- {1,0,1,0,0},
- {0,1,0,1,1},
- {1,0,1,0,1},
- {0,0,1,1,0}
- };
- ArrayToList(A[0], 5, G);
-
- printf(" 由2开始广度遍历:");
- BFS(G, 2);
-
- printf(" 由0开始广度遍历:");
- BFS(G, 0);
- return 0;
- }
- </span>
运算结果:
![](https://img-blog.csdn.net/20161124102402409?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
知识点总结:
图的两种遍历
学习心得:
两种遍历比较容易掌握,相对来说要理解好深度优先遍历的内容,并且要避免出现回路。