1. 程式人生 > >資料結構之基於圖的廣度優先搜尋,判斷無向圖的連通性

資料結構之基於圖的廣度優先搜尋,判斷無向圖的連通性

#include <iostream>


using namespace std;


struct LinkNode
{
int data;
LinkNode *next;
};


struct LinkQueue
{
LinkNode *front;
LinkNode *rear;
};


void init(LinkQueue *&Q)
{
Q=new LinkQueue;
Q->front=new LinkNode;
Q->front->next=0;
Q->rear=Q->front;
}


bool isEmpty(LinkQueue *Q)
{
return Q->rear==Q->front;
}


bool isNotEmpty(LinkQueue *Q)
{
return Q->rear!=Q->front;
}


void push(LinkQueue *&Q,int e)
{
LinkNode *p=new LinkNode;
p->data=e;
p->next=0;
Q->rear->next=p;
Q->rear=p;
}


int pop(LinkQueue *&Q)
{
if(isNotEmpty(Q))
{
LinkNode *p=Q->front->next;
int d=p->data;
Q->front->next=p->next;
if(Q->rear==p)
Q->rear=Q->front;
delete p;
return d;
}
}


const int n=5;


int G[n][n]={ {0,1,0,0,0},
  {1,0,1,0,1},
  {0,1,0,0,1},
  {0,0,0,0,0},
  {0,1,1,0,0}, };


int visited[n];


void init()
{
for(int v=1;v<=n;v++)
visited[v]=0;
}


bool BFS(LinkQueue *&Q,int v)
{
visited[v]=1;
push(Q,v);
int c=0;
while(isNotEmpty(Q))
{
v=pop(Q);
c++;
cout<<"v"<<v+1<<endl;
for(int w=0;w<n;w++)
{
if(G[v][w] && (!visited[w]))
{
visited[w]=1;
push(Q,w);
}
}
}
if(c==n)
return true;
return false;
}


int main()
{
LinkQueue *Q;
init(Q);

init();

if(BFS(Q,0))
cout<<"ok"<<endl;
else
cout<<"no"<<endl;

return 0;
}