树的广度深度优先遍历
#include <iostream>
#include <iomanip>
#include <queue>
using namespace std;
#define MaxNum 20
#define ERROR -1
bool visited[MaxNum];
typedef enum {DG,DN,UDG,UDN}GraphKind;
typedef struct ArcCell
{
int adj; //
}ArcCell,AdjMatrix[MaxNum][MaxNum];
typedef struct
{
char vexs[MaxNum]; //顶点向量
AdjMatrix arcs; //邻接矩阵
int vexnum,arcnum; //顶点数,弧数
GraphKind kind; //枚举类型
}MGraph;
void CreateUDN(MGraph &G) //创建一个图
{
int v1,v2,w,j=0,int_max=0;
cout<<"请输入顶点数和弧数:"<<endl;
cin>>G.vexnum>>G.arcnum;
cout<<"请输入顶点向量:"<<endl;
for(int 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].adj=int_max;
cout<<"请输入顶点的坐标及权值w:"<<endl;
for(int k=0;k<G.arcnum;k++)
{
cin>>v1>>v2>>w;
i=v1;j=v2;
G.arcs[i][j].adj=w;
G.arcs[j][i]=G.arcs[i][j];
}
}
int MUDGFirstVertex(MGraph &G) //求图的第一个顶点
{
return G.vexnum==0?ERROR:0;
}
int MUDGNextVertex(MGraph &G,int i) //求图的相对于i的第一个顶点
{
return i==G.vexnum-1?ERROR:i+1;
}
int MUDGFirstAdjacent(MGraph &G,int i) //求图中与顶点i邻接的第一个顶点
{
for(int k=0;k<G.vexnum;k++)
if(G.arcs[i][k].adj!=0)
return k;
return ERROR;
}
int MUDGNextAdjacent(MGraph &G,int i,int j) //求图中与顶点i相对于顶点j邻接的第一个顶点
{
for(int k=j+1;k<G.vexnum;k++)
if(G.arcs[i][k].adj!=0)
return k;
return ERROR;
}
void DFS(MGraph &G,int i) //连通图的深度优先遍历
{
visited[i]=true;
cout<<G.vexs[i];
for(int w=MUDGFirstAdjacent(G,i);w>=0;w=MUDGNextAdjacent(G,i,w))
if(!visited[w])
{
cout<<"->";
DFS(G,w);
}
}
void DFSTraverse(MGraph &G) //非连通图的深度优先遍历;
{
cout<<"深度优先遍历:"<<endl;
for(int i=0;i<G.vexnum;i++)
visited[i]=false;
for(i=0;i<G.vexnum;i++)
if(!visited[i])
DFS(G,i);
cout<<endl;
}
void BFS(MGraph &G,int i) //连通图的广度优先遍历
{
int ch1,ch2; //广度优先遍历
queue<int> G1;
G1.push(i); //初始顶点入队列
cout<<G.vexs[i];
visited[i]=true; //初始顶点被访问过
while(!G1.empty())
{
ch1=G1.front();
G1.pop();
ch2=MUDGFirstAdjacent(G,ch1);
while(ch2!=ERROR) //邻接顶点存在是循环
{
if(visited[ch2]==false)
{ cout<<"->";
G1.push(ch2);
visited[ch2]=true;
cout<<G.vexs[ch2];
}
ch2=MUDGNextAdjacent(G,ch1,ch2); //图G中ch1相对于顶点ch2的下一个邻接顶点
}
}
/* int ch1,ch2; //广度优先遍历书中代码
queue<int> G1;
for(int m=0;m<G.vexnum;m++)
if(visited[m]==false)
{
G1.push(m);
visited[m]=true;
cout<<G.vexs[m]<<"->";
while(!G1.empty())
{
G1.pop();
for(int j=MUDGFirstAdjacent(G,m);j>=0;j=MUDGNextAdjacent(G,m,j))
if(!visited[j])
{
visited[j]=true;
cout<<G.vexs[j]<<"->";
G1.push(j);
}
}
}*/
}
void BFSTraverse(MGraph &G) //非连通图的广度优先遍历
{
cout<<"广度优先遍历:"<<endl;
int i;
for(int j=0;j<G.vexnum;j++)
visited[j]=false;
for(i=MUDGFirstVertex(G);i!=ERROR;i=MUDGNextVertex(G,i))
if(visited[i]==false)
BFS(G,i);
}
int main()
{
MGraph MG;
CreateUDN(MG);
DFSTraverse(MG); //深度优先遍历
BFSTraverse(MG); //广度优先遍历
cout<<endl;
return 0;
}
/*5 6
A B C D E
0 1 1
0 3 1
1 2 1
1 4 1
2 3 1
2 4 1 */
浙公网安备 33010602011771号