1. 程式人生 > >無向圖的建立和兩種遍歷

無向圖的建立和兩種遍歷



// ConsoleApplication2.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
#define maxSize (100)
typedef struct ArcNode{//弧結點
 int info;//弧資訊
 struct ArcNode* nextarc;//指向下一個弧結點的指標
 int adjvex;//弧指向結點在順序表中的序號
}ArcNode;

typedef struct VNode{//定點結點
 char data;//定點結點值
 ArcNode*firstarc;//指向的第一條弧結點
}VNode;

typedef struct AGraph{
 VNode adjlist[maxSize];//頂點列表
 int e, n;//弧和頂點數目
}AGraph;

int adjloction(AGraph*G, char v)//查詢頂點值為v的頂點在順序連結串列中的位置
{
 for (int i = 0; i < G->n; ++i)
  if (G->adjlist[i].data == v)
   return i;
 return -1;
}
void CreateAGraph(AGraph *&G)//建立圖
{
 G = (AGraph*)malloc(sizeof(AGraph));
 cout << "輸入頂點數和弧數:" << endl;
 cin >> G->n >> G->e;

 cout << "輸入頂點:" << endl;
 for (int i = 0; i < G->n; ++i)
 {
  cin >> G->adjlist[i].data;
  G->adjlist[i].firstarc = NULL;
 }

 cout << "輸入弧:" << endl;
 for (int i = 0; i < G->e; ++i)
 {
  ArcNode *arc = (ArcNode*)malloc(sizeof(ArcNode));
  char v1, v2;
  int a1, a2;
  cin >> v1 >> v2;
  a1 = adjloction(G, v1);
  a2 = adjloction(G, v2);
  arc->adjvex = a2;
  //cin >> arc->info;
  arc->nextarc = G->adjlist[a1].firstarc;
  G->adjlist[a1].firstarc = arc;

  arc = (ArcNode*)malloc(sizeof(ArcNode));
  arc->adjvex = a1;
  //cin>>arc->info;
  arc->nextarc = G->adjlist[a2].firstarc;
  G->adjlist[a2].firstarc = arc;
 }
}

void Print(AGraph *G)//列印鄰接表
{
 ArcNode *p;
 for (int i = 0; i < G->n; ++i)
 {
  cout << G->adjlist[i].data<<endl;
  p = G->adjlist[i].firstarc;//p為第一條弧
  while (p)
  {
   cout << " ->" << G->adjlist[p->adjvex].data<<endl;
   p = p->nextarc;
  }
 }
}

int visit[maxSize];
void DFS(AGraph*G, char v)//深搜
{
 cout << G->adjlist[adjloction(G, v)].data << endl;
 visit[adjloction(G, v)] = 1;//標記已搜尋
 ArcNode*p = G->adjlist[adjloction(G, v)].firstarc;
 while (p)
 {
  if (visit[p->adjvex] != 1)
   DFS(G, G->adjlist[p->adjvex].data);
  p = p->nextarc;
 }
}

void BFS(AGraph*G, char v)//廣搜
{
 int queue[maxSize];
 int mvisit[maxSize];
 int rear=0,  front = 0;
 int j;

 cout << v << endl;
 mvisit[adjloction(G, v)] = 1;

 rear = (rear + 1) % maxSize;
 queue[rear] = adjloction(G, v);

 while (rear!=front)//佇列是否為空
 {
  front = (front + 1) % maxSize;
  j = queue[front];
  //cout << G->adjlist[j].data << endl;
  //mvisit[j] = 1;//標記為已訪問
  ArcNode*p = G->adjlist[j].firstarc;
  while (p)
  {
   if (mvisit[p->adjvex] != 1)
   {
    cout << G->adjlist[p->adjvex].data << endl;
    mvisit[p->adjvex] = 1;
    rear = (rear + 1) % maxSize;
    queue[rear] = p->adjvex;
   }
   p = p->nextarc;
  }
 }
}
int _tmain(int argc, _TCHAR* argv[])
{
 AGraph*G;
 CreateAGraph(G);
 cout << "列印鄰接表:" << endl;
 Print(G);
 cout << "列印深度優先搜尋結果:" << endl;
 DFS(G, G->adjlist[0].data);
 cout << "列印廣度優先搜尋結果:" << endl;
 BFS(G, G->adjlist[0].data);
 return 0;
}