1. 思想
从已发现的顶点集合F中拿出一个顶点,访问该顶点,将该顶点的所有相邻且未被发现的顶点加入F,继续执行上述操作,直至F为空。
若F为栈,则是深度优先,为队列,则是广度优先。
2. 图度优先遍历(DFS)
void DFS(MGraph G) //栈实现DFS
{
stack<int> visit; //栈,已发现,未访问过的点
int flag[MaxVex]; //标记已访问过的点
for (int i = 0; i < G.numVer; i++)
flag[i] = 0;
int key = 0; //先入栈再访问
visit.push(key);
while (!visit.empty())
{
key = visit.top();
cout << G.ver[key] << " ";
visit.pop();
flag[key] = 1;
for (int i = 0; i < G.numVer; i++)
{
if (G.arc[i][key] != INFINITY && flag[i] == 0)
{
visit.push(i);
flag[i] = 2;
}
}
}
}
3. 广度优先遍历(BFS)
void BFS(MGraph G) //队列实现BFS
{
queue<int> visit; //队列,已发现,未访问过的点
int flag[MaxVex]; //标记已访问过的点
for (int i = 0; i < G.numVer; i++)
flag[i] = 0;
int key = 0; //先入队再访问
visit.push(key);
while (!visit.empty())
{
key = visit.front();
cout << G.ver[key] << " ";
visit.pop();
for (int i = 0; i < G.numVer; i++)
{
if (G.arc[i][key] != INFINITY && flag[i] == 0)
{
visit.push(i);
flag[i] = 1; //表示已被发现加入队列
}
}
}
}
4. 完整代码
图
#include <stdio.h>
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef char VertexType;
typedef int EdgeType;
#define MaxVex 100
#define INFINITY 65535
typedef struct
{
VertexType ver[MaxVex];
EdgeType arc[MaxVex][MaxVex];
int numVer, numEdge;
}MGraph;
MGraph CreatGraph(MGraph G)
{
cout << "输入顶点数和边数" << endl;
cin >> G.numVer >> G.numEdge;
cout << "输入顶点信息" << endl;
for (int i = 0; i < G.numVer; i++)
cin >> G.ver[i];
for (int i = 0; i < G.numVer; i++)
for (int j = 0; j < G.numVer; j++)
G.arc[i][j] = INFINITY;
cout << "输入边信息 i j w" << endl;
int k, w;
for (int i = 0; i < G.numEdge; i++)
{
cin >> k >> w;
cin >> G.arc[k][w];
G.arc[w][k] = G.arc[k][w];
}
return G;
}
void DFS(MGraph G) //栈实现DFS
{
stack<int> visit; //栈,已发现,未访问过的点
int flag[MaxVex]; //标记已访问过的点
for (int i = 0; i < G.numVer; i++)
flag[i] = 0;
int key = 0; //先入栈再访问
visit.push(key);
while (!visit.empty())
{
key = visit.top();
cout << G.ver[key] << " ";
visit.pop();
flag[key] = 1;
for (int i = 0; i < G.numVer; i++)
{
if (G.arc[i][key] != INFINITY && flag[i] == 0)
{
visit.push(i);
flag[i] = 2;
}
}
}
}
void BFS(MGraph G) //队列实现BFS
{
queue<int> visit; //队列,已发现,未访问过的点
int flag[MaxVex]; //标记已访问过的点
for (int i = 0; i < G.numVer; i++)
flag[i] = 0;
int key = 0; //先入队再访问
visit.push(key);
while (!visit.empty())
{
key = visit.front();
cout << G.ver[key] << " ";
visit.pop();
for (int i = 0; i < G.numVer; i++)
{
if (G.arc[i][key] != INFINITY && flag[i] == 0)
{
visit.push(i);
flag[i] = 1; //表示已被发现加入队列
}
}
}
}
int main()
{
MGraph G ;
G.numVer=5;
G.numEdge = 5;
G.ver[0] = 'a';
G.ver[1] = 'b';
G.ver[2] = 'c';
G.ver[3] = 'd';
G.ver[4] = 'e';
for (int i = 0; i < G.numVer; i++)
for (int j = 0; j < G.numVer; j++)
G.arc[i][j] = INFINITY;
G.arc[0][1] = 1;
G.arc[0][2] = 2;
G.arc[1][4] = 4;
G.arc[1][3] = 4;
G.arc[2][4] = 4;
G.arc[1][0] = 1;
G.arc[2][0] = 2;
G.arc[4][1] = 4;
G.arc[3][1] = 4;
G.arc[4][2] = 4;
//G = CreatGraph(G);
BFS(G);
return 0;
}