#include"head.h" extern 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; }
}
<pre class="cpp" name="code">[cpp] view plaincopyprint? 01.#include"head.h" 02.int visited[MAXV]; 03.int main() 04.{ 05. int i; 06. ALGraph *G; 07. int A[5][5]= 08. { 09. {0,1,0,1,0}, 10. {1,0,1,0,0}, 11. {0,1,0,1,1}, 12. {1,0,1,0,1}, 13. {0,0,1,1,0} 14. }; 15. ArrayToList(A[0], 5, G); 16. 17. for(i=0; i<MAXV; i++) 18. visited[i]=0; 19. printf(" 由2开始深度遍历:"); 20. DFS(G, 2); 21. printf("\n"); 22. 23. for(i=0; i<MAXV; i++) 24. visited[i]=0; 25. printf(" 由0开始深度遍历:"); 26. DFS(G, 0); 27. printf("\n"); 28. return 0; 29.}
#include"head.h" extern visited[MAXV]; 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; //v进队 while (front!=rear) //若队列不空时循环 { front=(front+1)%MAXV; w=queue[front]; //出队并赋给w p=G->adjlist[w].firstarc; //找w的第一个的邻接点 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"); }
01.#include"head.h" 02.int visited[MAXV]; 03. 04.int main() 05.{ 06. ALGraph *G; 07. int A[5][5]= 08. { 09. {0,1,0,1,0}, 10. {1,0,1,0,0}, 11. {0,1,0,1,1}, 12. {1,0,1,0,1}, 13. {0,0,1,1,0} 14. }; 15. ArrayToList(A[0], 5, G); 16. 17. printf(" 由2开始广度遍历:"); 18. BFS(G, 2); 19. 20. printf(" 由0开始广度遍历:"); 21. BFS(G, 0); 22. return 0; 23.}