图的广度优先遍历
图这一章我一直觉得自己没学好。。。所以这次就直接放代码,不多说什么了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| typedef int Boolean; Boolean visited[MAXVEX];
#define QElemType int #define MAXSIZE 1000
typedef struct { QElemType data[MAXSIZE]; int front; int rear; }SqQueue;
Status InitQueue(SqQueue *Q){ if (!Q)return ERROR; Q->front = 0; Q->rear = 0; return OK; }
Status IsQueueEmpty(SqQueue Q){ if (Q.rear == Q.front)return TRUE; else{ return FALSE; } }
Status EnQueue(SqQueue *Q, QElemType e){ if ((Q->rear + 1) % MAXSIZE == Q->front)return ERROR; Q->data[Q->rear] = e; Q->rear = (Q->rear + 1) % MAXSIZE; return OK; }
Status DeQueue(SqQueue *Q, QElemType *e){ if (Q->front == Q->rear)return ERROR; *e = Q->data[Q->front]; Q->front = (Q->front + 1) % MAXSIZE; return OK; }
void BFSTraverse(GraphAdjList G){ int i; SqQueue Q; EdgeNode* p;
for (i = 0; i < G.numVertexes; i++){ visited[i] = FALSE; }
InitQueue(&Q);
for (i = 0; i < G.numVertexes; i++){ if (!visited[i]){ visited[i] = TRUE; printf("%c", G.adjList[i].data); EnQueue(&Q, i); while (!IsQueueEmpty(Q)){ DeQueue(&Q, &i); p = G.adjList[i].firstedge; while (p){ if (!visited[p->adjvex]){ printf("%c", G.adjList[p->adjvex].data); EnQueue(&Q, p->adjvex); } p = p->next; } } } } }
|