这里我采用邻接矩阵的存储方式对图进行遍历
#include <iostream>
#include <queue>
#define INFINITY 100
#define MAXNODE 100
#define OK 1
using namespace std;
typedef char VertexType;
int vis[MAXNODE];
typedef struct
{
int adj;
} ArcType;
typedef struct
{
VertexType vertexs[MAXNODE];
ArcType arc[MAXNODE][MAXNODE];
int vexnum,arcnum;
} GraphType;
int LocateVex(GraphType *G,VertexType v)
{
int i=-1;
for(int k=0; k<G->vexnum; k++)
{
if(G->vertexs[k]==v)
{
i=k;
break;
}
}
return i;
}
int CreatDN(GraphType *G) //创建一个无向图
{
cout<<"输入图的顶点数:";
cin>>G->vexnum;
cout<<"输入图的边数:";
cin>>G->arcnum;
for(int i=0; i<G->vexnum; i++)
{
for(int j=0; j<G->vexnum; j++)
{
G->arc[i][j].adj=0;
}
}
cout<<"输入图的顶点:";
for(int i=0; i<G->vexnum; i++)
{
cin>>G->vertexs[i];
}
cout<<"输入弧的顶点:";
VertexType v1,v2;
int locate1,locate2;
for(int i=0; i<G->arcnum; i++)
{
cin>>v1>>v2;
locate1=LocateVex(G,v1);
locate2=LocateVex(G,v2);
G->arc[locate1][locate2].adj=1;
G->arc[locate2][locate1].adj=1;
}
return OK;
}
void DFS(GraphType G,int v) //图的深度遍历
{
cout<<G.vertexs[v]<<" ";
vis[v]=1;
for(int i=0; i<G.vexnum; i++)
{
if(!vis[i]&&G.arc[v][i].adj==1)
{
DFS(G,i);
}
}
}
//int counter;
void DFSTraveGraph(GraphType G)
{
for(int i=0; i<G.vexnum; i++)
{
vis[i]=0;
}
for(int i=0; i<G.vexnum; i++)
{
if(!vis[i])
{
//counter++; 计算连通度
DFS(G,i);
}
}
}
queue<int> q;
void BFS(GraphType G,int v)
{
cout<<G.vertexs[v]<<" ";
vis[v]=1;
q.push(v);
int cut;
while(!q.empty())
{
cut=q.front();
q.pop();
for(int i=0; i<G.vexnum; i++)
{
if(!vis[i]&&G.arc[i][cut].adj==1)
{
cout<<G.vertexs[i]<<" ";
vis[i]=1;
q.push(i);
}
}
}
}
void BFSTraveGraph(GraphType G) //图的广度遍历
{
for(int i=0; i<G.vexnum; i++)
{
vis[i]=0;
}
for(int i=0; i<G.vexnum; i++)
{
if(!vis[i])
{
BFS(G,i);
}
}
}
int main()
{
GraphType G;
cout<<"————创建一个无向图————"<<endl;
CreatDN(&G);
cout<<"深度优先遍历:"<<endl;
DFSTraveGraph(G);
cout<<endl;
cout<<"广度优先遍历:"<<endl;
BFSTraveGraph(G);
cout<<endl;
//cout<<counter<<endl; 计算该图的连通度
return 0;
}