#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define MVNum 100
#define MAXQSIZE 100
typedef int Vtype;
typedef struct
{
Vtype vexs[MVNum];
int arcs[MVNum][MVNum];
int vexnum,arcnum;
}Graph;
typedef struct{
int *base;
int front;
int rear;
}sqQueue;
void InitQueue(sqQueue &Q){
Q.base = new int[MAXQSIZE];
if(!Q.base) exit(1);
Q.front = Q.rear = 0;
}
void EnQueue(sqQueue &Q, int e){
if((Q.rear + 1) % MAXQSIZE == Q.front)
return;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
}
bool QueueEmpty(sqQueue Q){
if(Q.rear == Q.front)
return true;
return false;
}
void DeQueue(sqQueue &Q, int &u){
u = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
}
bool visited[MVNum];
int FirstAdj(Graph G,int v)
{
int i;
for(i=0;i<G.vexnum;i++)
{
if(G.arcs[v][i]==1&&visited[i]==false)
return i;
}
return -1;
}
int NextAdj(Graph G,int v,int w)
{
int i;
for(i=w;i<G.vexnum; i++)
{
if(G.arcs[v][i]==1&&visited[i]==false)
return i;
}
return -1;
}
int localvex(Graph G,int v)
{
for(int i=0;i<G.vexnum;++i)
if(G.vexs[i]==v) return i;
return -1;
}
void CreateUDN(Graph &G)
{
int i,j,k;
cout<<"请输入总顶点数和总边数" ;
cin>>G.vexnum>>G.arcnum;
cout<<endl;
cout<<"输入点的信息";
for(i=0;i<G.vexnum;++i)
cin>>G.vexs[i];
for(i=0;i<G.vexnum;++i)
for(j=0;j<G.vexnum;++j)
G.arcs[i][j]=0;
for(k=0;k<G.arcnum;++k)
{
int v1,v2;
cout<<"输入第"<<(k+1)<<"边依附的顶点";
cin>> v1>>v2;
i=localvex(G,v1); j=localvex(G,v2);
G.arcs[j][i]=G.arcs[i][j]=1;
}
}
void DFS(Graph G,Vtype v)
{
int w;
cout<< G.vexs[v] << " ";visited[v]=true;
for(w=0;w<G.vexnum;++w)
if((G.arcs[v][w]==1)&&(!visited[w])) DFS(G,w);
}
void BFS (Graph G, int v){
memset(visited,false,sizeof(visited));
sqQueue Q;
int u;
int w;
cout << G.vexs[v] << " "; visited[v] = true;
InitQueue(Q);
EnQueue(Q, v);
while(!QueueEmpty(Q)){
DeQueue(Q, u);
for(w = FirstAdj(G, u); w >= 0; w = NextAdj(G, u, w)){
if(!visited[w]){
visited[w] = true;
EnQueue(Q, w); cout << G.vexs[w] << " ";
}
}
}
}
int main(){
Graph G;
CreateUDN(G);
cout << endl;
cout << "无向图G创建完成!" << endl << endl;
cout << "请输入遍历无向图G的起始点:";
Vtype c;
cin >> c;
int i;
for(i = 0 ; i < G.vexnum ; ++i){
if(c == G.vexs[i])
break;
}
cout << endl;
while(i >= G.vexnum){
cout << "该点不存在,请重新输入!" << endl;
cout << "请输入遍历连通图的起始点:";
cin >> c;
for(i = 0 ; i < G.vexnum ; ++i){
if(c == G.vexs[i])
break;
}
}
cout << "深度优先搜索遍历无向图G结果:" << endl;
DFS(G , i);
cout << "广度优先搜索遍历连通图结果:" << endl;
BFS(G , i);
cout <<endl;
return 0;
}