图是一种多对多的关系,有深度优先和广度优先两个遍历方式,下面用代码简单介绍一下。
#include //添加头文件
#include //添加头文件
#include //添加头文件
using namespace std;
stack st; //栈
queue qu; //队列
//邻接表类型 定义存储方式
typedef struct ArcNode
{
int adjvex;
ArcNode * nextarc;
int info;
} ArcNode;
#define MVNum 100
int vis[MVNum]; //标记数组
typedef struct VNode //点结构
{
string data;
ArcNode *firstarc; //第一条边的指针
} VNode,AdjList[MVNum];
typedef struct
{
AdjList vertices;
int vexnum,arcnum; //顶点数和边数
} ALGraph;
//邻接矩阵类型
typedef struct
{
string vexs[MVNum]; //顶点表
int arcs[MVNum][MVNum]; //邻接矩阵
int vexnum,arcnum; //图的顶点数和边数
} AMGraph;
广度优先遍历
void BFS(ALGraph G, int v) //邻接表
{
//memset(vis,0,sizeof vis);
qu=queue();
cout<<v<<" ";
//按广度优先非递归遍历连通图G
vis[v] = true; //访问第v个顶点
//InitQueue(Q); //辅助队列Q初始化,置空
//EnQueue(Q, v);
qu.push(v); //v进队
while(!qu.empty()) //队列非空
{
int tmp=qu.front();
qu.pop();
ArcNode *p=G.vertices[tmp].firstarc;
while(p!=NULL)
{
int w=p->adjvex;
if(!vis[w])
{
cout<<w<<" ";
vis[w]=1;
qu.push(w);
}
p=p->nextarc;
}
cout<<endl;
}//BFS
}
深度优先遍历
void DFS_AM(AMGraph G, int v) //图G为邻接矩阵类型
{
cout<<v<<" ";
vis[v] = true; //访问第v个顶点
for(int w = 0; w< G.vexnum; w++) //依次检查邻接矩阵v所在的行
if((G.arcs[v][w]!=0) && (!vis[w]))
DFS_AM(G, w);
//w是v的邻接点,如果w未访问,则递归调用DFS
}
void FindD0(AMGraph G,int v)
{
//memset(vis,0,sizeof vis);
DFS_AM(G,v);
cout<<endl;
}
以上就是对图遍历的两种方式,希望对大家的学习有帮助。