利用邻接矩阵做图的存储结构来进行深度搜索遍历以及广度搜索遍历
//二维数组存储邻接矩阵
//一维数组存储顶点信息
#include<iostream>
using namespace std;
//-----图的邻接矩阵表示----
#define MaxInt 0000 //表示极大值
#define MVNum 100 //最大顶点数
typedef string VerTexType;//假设顶点的数据类型为字符串型
typedef int ArcType; //假设边的权值类型为字符串型
typedef struct
{
VerTexType vexs[MVNum];//顶点表
ArcType arcs[MVNum][MVNum];//邻接矩阵
int vexnum, arcnum;//图的当前顶点数和边数
}AMGraph;
//采用邻接矩阵表示法创建无向网
/*
1.输入总顶点数和总边数
2.依次输入点的信息并将其存入顶点表中
3.初始化邻接矩阵,使每个权值初始化为极大值
4.构造邻接矩阵,依次输入每条边依附的顶点和其权值,确定两个顶点在图中的位置之后,使相应边赋予相应的权限,
同时使其对称边赋予相同的权值*/
//返回顶点在邻接矩阵中对应的下标
int LocateVex(AMGraph& G, char *v1)
{
for (int i = 0; i<G.vexnum; i++)
{
if (v1 == G.vexs[i])
return i;
}
}
void CreateUDN(AMGraph& G)
{
int i, j, k,w;
string v1,v2;
cin >> G.vexnum >> G.arcnum; //输入总顶点数和总边数
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] = MaxInt; //初始化邻接矩阵,使每个权值初始化为极大值
for (k = 0; k < G.arcnum; ++k) //构造邻接矩阵
{
cin >> v1 >> v2 >> w; //输入一条边依附的顶点及其权值
i = LocateVex(G, &v1[0]); //确定v1和v2在G中的位置,即顶点数组的下标
j = LocateVex(G, &v2[0]);
G.arcs[i][j] = w; //边<v1,v2>的权值置为w
G.arcs[j][i] = G.arcs[i][j]; //置<v1,v2>的对称边<v2,v1>权值为w
}
for (int i = 0; i < G.vexnum; i++)
{
for (int j = 0; j < G.vexnum; j++)
{
// if (G.arcs[i][j] == MaxInt)
cout << G.arcs[i][j] << "\t";
/// else
// cout << G.arcs[i][j] << "\t";
}
cout << endl<<endl;
}
}//——————利用递归思想进行深度搜索遍历——————
bool visited[MVNum];
void DFS(AMGraph &G, int v)//v为起始点
{
int w;
cout<<G.vexs[v]<<" ";
visited[v]=true;
for(w=0;w<G.vexnum;w++)
if((G.arcs[v][w]!=0)&&(!visited[w]))
DFS(G,w);//递归思想,一层套一层,事半功倍
}
//——————利用队列进行广度搜索遍历使得先访问的点的邻接点也先被访问————
#define MAXSIZE 20
typedef struct
{
int *base;
int rear;
int front;
}Queue;
void initQueue(Queue &S)
{
S.base=new int[MAXSIZE];//分配一个数组空间
if(!S.base)
exit(0);
S.front=S.rear=0;
}
//???怎么判断队列是否满了?
void enQueue(Queue &Q,int v)
{
if((Q.rear+1)%MAXSIZE==Q.front)
{
cout<<"队列已满"<<endl;
exit(0);
}
Q.base[Q.rear]=v;
Q.rear=(Q.rear+1)%MAXSIZE;//因为循环,所以取余
}
void deQueue(Queue &Q,int &e)
{
if(Q.front==Q.rear)
{
cout<<"队列已空"<<endl;
exit(0);
}
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXSIZE;//+1就+1,为什么还要%
}
bool Queueempty(Queue &Q)
{
if(Q.front==Q.rear)//空了
return true;
else //非空0
return false;
}//visited[MVNum]={false};//???为什么会错?
bool visit[MVNum]={false};
void BFS(AMGraph G,int v)
{
int w,u;
Queue Q;
cout<<G.vexs[v]<<" ";
visit[v]=true;
initQueue(Q);
enQueue(Q,v);
while(!Queueempty(Q))//整体来看,只要要求是:括号里面的东西!=0
{
//cout<<"qqq";
deQueue(Q,u);
for(w=0;w<G.vexnum;w++)
if((G.arcs[u][w]!=0)&&(!visit[w]))
{
cout<<G.vexs[w]<<" ";
visit[w]=true;
enQueue(Q,w);
}
}
}
int main()
{
AMGraph G;
string v1,v2;
CreateUDN(G);
cout<<"输入深度搜索遍历起始顶点:"<<endl;
cin>>v1;
DFS(G,LocateVex(G,&v1[0]));
cout<<endl;
cout<<"输入广度搜索遍历起始顶点:"<<endl;
cin>>v2;
BFS(G,LocateVex(G,&v2[0]));
}
测试输入:
/*
8 9
v1 v2 v3 v4 v5 v6 v7 v8
v1 v2 10
v1 v3 20
v2 v4 30
v2 v5 40
v4 v8 50
v5 v8 60
v3 v6 70
v3 v7 80
v6 v7 90
*/