图--广度优先遍历/深度优先遍历(c语言实现)

  //不能通过编译,没有引入队列头文件
1
#include<stdlib.h> 2 #define MAX_VERTEX_NUM; 3 typedef int infoType; 4 typedef int vertexType; 5 6 typedef struct ArcNode{ 7 int adjvex; 8 struct ArcNode *next; 9 infoType *weight; 10 }Arcnode; 11 12 typedef struct VNode{ 13 vertexType data; 14 Arcnode *firstarc; 15 }VNode; 16 17 //VNode G[MAX_VERTEX_NUM]; 18 void getdata(VNode v); 19 20 //图的创建 21 void createGraph(int n,VNode G[]){ 22 int i,e; 23 Arcnode *p,*q; 24 printf("input the information of the vertex "); 25 for(i=0;i<n;i++){ 26 getdata(G[i]); 27 G[i].firstarc=NULL; 28 } 29 for(i=0;i<n;i++){ 30 printf("create the edges for the %dth vertex ",i); 31 scanf("%d",&e); 32 while(e!=-1){ 33 p=(Arcnode *)malloc(sizeof(Arcnode)); 34 p->next=NULL; 35 p->adjvex=e; 36 if(G[i].firstarc==NULL){ 37 G[i].firstarc=p; 38 }else{ 39 q->next=p; 40 } 41 q=p; 42 scanf("%d",&e); 43 } 44 } 45 } 46 47 //图的遍历(1)--深度优先搜索 48 void DFS(VNode g[],int v,int visited[]){ 49 int w; 50 visit(v); 51 visited[v]=1; 52 w=FirstAdj(g,v); 53 while(w!=-1){ 54 if(visited[w]==0) 55 DFS(g,w,visited); 56 w=nextAdj(g,v); 57 } 58 59 } 60 61 void DFSGraph(VNode g[],int visited[],int n){ 62 int i; 63 for(i=0;i<n;i++){ 64 visited[i]=0; 65 } 66 for(i=0;i<n;i++){ 67 if(visited[i]==0) 68 DFS(g,i,visited); 69 } 70 } 71 72 73 //图的遍历(2)--广度优先搜索 74 75 void BFS(VNode G[],int v,int visited[]){ 76 int w; 77 visit(v); 78 visited[v]=1; 79 EnQueue(q,v); 80 while(!emptyA(q)){ 81 Dequeue(&q,&v); 82 w=FirstAdj(g,v); 83 while(w!=-1){ 84 if(visited[w]==0){ 85 visit(w); 86 EnQueue(q,w); 87 visited[w]=1; 88 } 89 w=NextAdj(g,v); 90 } 91 } 92 } 93 94 void Travel_BFS(VNode g[],int visited[],int n){ 95 int i; 96 for(i=0;i<n;i++){ 97 visited[i]=0; 98 } 99 for(i=0;i<n;i++){ 100 if(visited[i]==0) 101 BFS(g,i,visited); 102 } 103 }
原文地址:https://www.cnblogs.com/mozhuhao/p/4487652.html