图这一章我一直觉得自己没学好。。。所以这次就直接放代码,不多说什么了

    1. typedef int Boolean; //Boolean是布尔类型,其值为TRUE 或者FLASE
    2. Boolean visited[MAXVEX]; //访问标志的数组
    3. #define QElemType int // 元素类型定义为图结点
    4. #define MAXSIZE 1000
    5. typedef struct {
    6. QElemType data[MAXSIZE];
    7. int front;
    8. int rear;
    9. }SqQueue;
    10. /*----------以下为队列的基本操作函数----------*/
    11. /*初始化一个空队列*/
    12. Status InitQueue(SqQueue *Q){
    13. if (!Q)return ERROR; //若空间分配失败,则返回ERROR
    14. Q->front = 0;
    15. Q->rear = 0;
    16. return OK;
    17. }
    18. /*判断SqQueue是否为空*/
    19. Status IsQueueEmpty(SqQueue Q){
    20. if (Q.rear == Q.front)return TRUE; //若尾指针指向头指针,则为空队列,返回TRUE
    21. else{ return FALSE; } //否则返回FALSE
    22. }
    23. /*插入元素e为新的队尾元素*/
    24. Status EnQueue(SqQueue *Q, QElemType e){
    25. if ((Q->rear + 1) % MAXSIZE == Q->front)return ERROR; // 若队列已满,则返回ERROR
    26. Q->data[Q->rear] = e; //e 入队列
    27. Q->rear = (Q->rear + 1) % MAXSIZE; //队尾指针后移
    28. return OK;
    29. }
    30. /*若队列不空,则删除队头元素,并用e返回其值*/
    31. Status DeQueue(SqQueue *Q, QElemType *e){
    32. if (Q->front == Q->rear)return ERROR; //若队列为空,则返回ERROR
    33. *e = Q->data[Q->front]; //若队列不为空,用e接收队头元素
    34. Q->front = (Q->front + 1) % MAXSIZE; //队头指针后移
    35. return OK;
    36. }
    37. /*----------队列的基本操作函数完----------*/
    38. /*----------以下为广度优先遍历算法---------*/
    39. void BFSTraverse(GraphAdjList G){
    40. int i;
    41. SqQueue Q;
    42. EdgeNode* p;
    43. for (i = 0; i < G.numVertexes; i++){
    44. visited[i] = FALSE;
    45. }
    46. InitQueue(&Q); //初始化一辅助用的队列
    47. for (i = 0; i < G.numVertexes; i++){ //对每一个顶点做循环
    48. if (!visited[i]){ //若未访问过,则如下处理
    49. visited[i] = TRUE; //将当前结点设为已访问
    50. printf("%c", G.adjList[i].data);//打印顶点,也可以改为其它操作
    51. EnQueue(&Q, i); //将该顶点入队列
    52. while (!IsQueueEmpty(Q)){
    53. DeQueue(&Q, &i); //将队头元素出队,并赋给e
    54. p = G.adjList[i].firstedge; //找到当前顶点边表头指针
    55. while (p){
    56. if (!visited[p->adjvex]){//若当前结点未被访问过
    57. printf("%c", G.adjList[p->adjvex].data);
    58. EnQueue(&Q, p->adjvex);
    59. }
    60. p = p->next; //指针指向下一个邻接点
    61. }
    62. }
    63. }
    64. }
    65. }

    瓦雀