王道考研 ++++ 圖的廣度優先搜索

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MaxSize 100
typedef struct EageTable  //邊表
{
  int eageData;           //值
  struct EageTable *next; //指向下一條弧
}EageTable;
typedef struct HeadTable  //頭表
{
  int headData;           //值
  EageTable *first;       //指向頭節點後第一個節點
}HeadTable,HeadList[MaxSize];
typedef struct
{
  HeadList Graph;
  int headNum,arcNum;     //頭節點書 弧數
}Graph;

typedef struct LQueue     //隊列
{
  int Queue[MaxSize];
  int front,rear;
}LQueue;
bool vis[MaxSize] = {false};

void InitQueue(LQueue *Q);
bool JudgeEmpty(LQueue *Q);
void EnQueue(LQueue *Q,int num);
int DeQueue(LQueue *Q);
int GetFront(LQueue *Q);
void InitGraph(Graph *G);
void CreateGraph(Graph *G,int flag,int a,int b);
void BFS(LQueue *Q,Graph *G,int front);
void TraverBFS(LQueue *Q,Graph *G,int start);
/*初始化隊列*/
void InitQueue(LQueue *Q)
{
  Q->front = Q->rear = 0;
}
/*判斷隊列是否爲空*/
bool JudgeEmpty(LQueue *Q)
{
  if(Q->front == Q->rear)return true;
  else return false;
}
/*進隊*/
void EnQueue(LQueue *Q,int num)
{
  Q->Queue[Q->rear++] = num;
}
/*出隊*/
int DeQueue(LQueue *Q)
{
  int temp = Q->Queue[Q->front];
  Q->front++;
  return temp;
}
int GetFront(LQueue *Q)
{
  return Q->Queue[Q->front];
}
/*初始化鄰接表的頭*/
void InitGraph(Graph *G)
{
  int i;
  for(i = 1;i <= G->headNum;i++)
  {
    G->Graph[i].headData = i;
    G->Graph[i].first = NULL;
  }
}
/*創建鄰接表*/
void CreateGraph(Graph *G,int flag,int a,int b)
{
  EageTable* eage;
  eage = (EageTable*)malloc(sizeof(EageTable));
  eage->eageData = b;
  //頭插入
  eage->next = G->Graph[a].first;
  G->Graph[a].first = eage;
  //圖爲無向圖時
  if(flag == 2)
  {
    EageTable* eagee;
    eagee = (EageTable*)malloc(sizeof(EageTable));
    eagee->eageData = a;

    eagee->next = G->Graph[b].first;
    G->Graph[b].first = eagee;
  }
}
/*廣搜*/
void BFS(LQueue *Q,Graph *G,int front)
{
    EageTable *eage = G->Graph[front].first;//eage區front節點的側表
    while(eage)//遍歷
    {
      if(vis[eage->eageData] == false)//沒被訪問的節點入棧 並 標誌節點已讀
      {
          EnQueue(Q,eage->eageData);
          vis[eage->eageData] = true;
      }
      eage = eage->next;
    }
}
void TraverBFS(LQueue *Q,Graph *G,int start)
{
  InitQueue(Q);
  EnQueue(Q,start);
  vis[start] = true;//標誌節點已讀
  while(!JudgeEmpty(Q))
  {
    int front = GetFront(Q);//獲取隊中第一個節點
    printf("%-2d",front);//輸出節點
    BFS(Q,G,front);
    DeQueue(Q);
  }
}
int main(int argc, char const *argv[]) {
  Graph G;
  LQueue Q;
  int i,flag,start;

  printf("有向圖輸入1,無向圖輸入2:");
  scanf("%d",&flag);
  printf("請輸入節點數:");
  scanf("%d",&G.headNum);
  InitGraph(&G);
  printf("請輸入弧的條數(從1開始):");
  scanf("%d",&G.arcNum);
  printf("請輸%d入條邊:\n",G.arcNum);
  for(i = 0;i < G.arcNum;i++)
  {
    int a,b;
    scanf("%d %d",&a,&b);
    CreateGraph(&G,flag,a,b);
  }
  printf("請輸入開始的節點:");
  scanf("%d",&start);
  TraverBFS(&Q,&G,start);
  return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章