1. 程式人生 > >鄰接表建立無向圖,廣度優先搜尋遍歷輸出

鄰接表建立無向圖,廣度優先搜尋遍歷輸出

  1 #include<stdio.h>
  2 #include<string.h>
  3 #include <iostream>
  4 #include<algorithm>
  5 using namespace std;
  6 #define MVNum 100
  7 int vis[MVNum];
  8 typedef struct ArcNode
  9 {
 10     int adjvex;
 11     int info;
 12     struct ArcNode *nextarc;
 13 } ArcNode;
14 typedef struct VNode 15 { 16 char data; 17 ArcNode *firstarc; 18 } VNode, AdjList[MVNum]; 19 typedef struct 20 { 21 AdjList vertices; 22 int vexnum,arcnum; 23 } ALGraph; 24 25 typedef struct 26 { 27 int *base;//儲存空間的基地址 28 int front;//頭指標 29 int rear;//尾指標 30
} SqQueue; 31 void InitQueue(SqQueue &Q) //初始化 32 { 33 Q.base=new int[MVNum]; 34 if(!Q.base) 35 printf("儲存分配失敗\n"); 36 Q.front=Q.rear=0; 37 } 38 int QueueEmpty(SqQueue Q) //求迴圈佇列是否為空 39 { 40 if(Q.front==Q.rear) 41 return 1; 42 else 43 return 0;
44 } 45 int EnQueue(SqQueue &Q,int e) //入隊 46 { 47 if((Q.rear+1)%MVNum==Q.front)//隊滿 48 return 0; 49 Q.base[Q.rear]=e; 50 Q.rear=(Q.rear+1)%MVNum; 51 return 1; 52 } 53 int DeQueue(SqQueue &Q,int &e) //出隊 54 { 55 if(Q.front==Q.rear)//隊滿 56 return 0; 57 e=Q.base[Q.front]; 58 Q.front=(Q.front+1)%MVNum; 59 return 1; 60 } 61 62 int LocateVex(ALGraph &G,char v)//找到v在鄰接表G中的位置 63 { 64 for(int i=0; i<G.vexnum; i++) 65 { 66 if(G.vertices[i].data==v) 67 return i; 68 } 69 return -1; 70 } 71 void CreateALGraph(ALGraph &G) 72 { 73 int i,j,k,v; 74 char v1,v2; 75 ArcNode *p1,*p2; 76 scanf("%d%d",&G.vexnum,&G.arcnum); 77 for(v = 0; v < G.vexnum; v++) 78 { 79 scanf("%s",&G.vertices[v].data); 80 G.vertices[v].firstarc=NULL; 81 } 82 getchar(); 83 for(k = 0; k < G.arcnum; k++) 84 { 85 scanf("%c %c",&v1,&v2); 86 getchar(); 87 i=LocateVex(G,v1); 88 j=LocateVex(G,v2); 89 p1=new ArcNode; 90 p1->adjvex=j; 91 p1->nextarc=G.vertices[i].firstarc; 92 G.vertices[i].firstarc=p1; 93 94 p2=new ArcNode; 95 p2->adjvex=i; 96 p2->nextarc=G.vertices[j].firstarc; 97 G.vertices[j].firstarc=p2; 98 } 99 } 100 101 void BFS(ALGraph G,int v) 102 { 103 SqQueue Q; 104 int u,w; 105 ArcNode *p; 106 printf("%c",v+'A'); 107 vis[v]=1; 108 InitQueue(Q); 109 EnQueue(Q,v); 110 while(!QueueEmpty(Q)) 111 { 112 DeQueue(Q,u); 113 p=G.vertices[u].firstarc; 114 115 while(p!=NULL) 116 { 117 w=p->adjvex; 118 if(!vis[w]) 119 { 120 printf("%c",w+'A'); 121 vis[w]=1; 122 EnQueue(Q,w); 123 } 124 p=p->nextarc; 125 } 126 } 127 } 128 int main(void) 129 { 130 ALGraph G; 131 memset(vis,0,sizeof(vis)); 132 CreateALGraph(G); 133 BFS(G,0); 134 return 0; 135 }
輸入:

8 9
A B C D E F G H
A B
B D
B E
E F
D F
A C
C G
C H
G H

輸出:

ACBHGEDF

鄰接表建立為:

A->C->B
B->E->D->A
C->H->G->A
D->F->B
E->F->B
F->D->E
G->H->C
H->G->C