本文列出邻接矩阵以及邻接链表表示的无向图的广度优先搜索C++源代码。代码依据下面无向图执行:
邻接矩阵表示的无向图的广度优先搜索:
head.h
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define N 6
#define INFINITE 0x7ffffff
enum Color{WHITE,GARY,BLACK};
struct Graph
{
int map[N+1][N+1];//存储图的矩阵
int distance[N+1];//与源节点之间的距离
int parent[N+1];//指向遍历结果的父节点
Color cor[N+1];//颜色
};
queue<int > LiQueue;
//向图中插入边
bool InsertEdge(Graph *G,int row,int col,int val)
{
G->map[row][col]=val;
return true;
}
//输出邻接矩阵表示的图
void Print(Graph *G)
{
/*cout<<" ";
for (int i=1;i<=N;i++)
{
cout<<i<<" ";
}
cout<<endl<<endl;*/
for (int i=1;i<=N;i++)
{
cout<<" ";
for (int j=1;j<=N;j++)
{
if(G->map[i][j]==1)
{
cout<<1<<" ";
}
else
cout<<0<<" ";
}
cout<<endl;
}
cout<<endl;
}
//初始化邻接表表示图,本例为无向图
bool Init_Graph(Graph *g)
{
InsertEdge(g,1,2,1);
InsertEdge(g,2,1,1);
InsertEdge(g,1,4,1);
InsertEdge(g,4,1,1);
InsertEdge(g,2,5,1);
InsertEdge(g,5,2,1);
InsertEdge(g,3,5,1);
InsertEdge(g,5,3,1);
InsertEdge(g,3,6,1);
InsertEdge(g,6,3,1);
I