#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//#define PATH
#define VERTEX_NUM 8
#ifdef PATH
int count = 1;
#endif
bool visited[VERTEX_NUM + 1]; // 访问标志数组(备忘表)
int FirstAdjVex(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1], int v)
{
for (int j = 1; j <= VERTEX_NUM; j++) {
if (G[v][j] == 1)
return j;
}
cout << "该点是孤立点" << endl; // 连通图则不会到这一步
return -1;
}
int NextAdjVex(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1], int v, int w)
{
for (int j = w + 1; j <= VERTEX_NUM; j++) {
if (G[v][j] == 1)
return j;
}
return -1;
}
void DFS(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1], int v)
{
// 从第v个顶点出发递归地深度优先遍历图G。
int w;
visited[v] = true;
cout << v << endl;
for (w = FirstAdjVex(G, v); w != -1; w = NextAdjVex(G, v, w)) {
#ifdef PATH
cout << "------------------" << count++ << "----" << v << "->" << w << endl; // 1
#endif
if (!visited[w]) { // 对v的尚未访问的邻接顶点w递归调用DFS
DFS(G, w);
#ifdef PATH
cout << v << endl; // 有待研究? // 2
#endif
}
}
#ifdef PATH
cout << "回溯路径" << v << "->"; // 3
#endif
}
void DFSTraverse(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1])
{
// 对图G作深度优先遍历。
int v;
for (v = 1; v <= VERTEX_NUM; ++v)
visited[v] = false; // 访问标志数组初始化
for (v = 1; v <= VERTEX_NUM; ++v) { // 若是连通图,则v=1即全遍历到
if (!visited[v])
DFS(G, v); // 对尚未访问的顶点调用DFS
}
}
int main(int argc, char **argv)
{
freopen("cin.txt", "r", stdin);
bool G[VERTEX_NUM + 1][VERTEX_NUM + 1] = {0};
int a;
int b;
while (cin >> a >> b, !(a == 0 && b == 0)) { //以0 0作为输入结束
G[a][b] = 1;
G[b][a] = 1;
}
for (int i = 1; i <= VERTEX_NUM; i++) { // 输出邻接矩阵
for (int j = 1; j <= VERTEX_NUM; j++) {
cout << G[i][j] << ' ';
}
cout << endl;
}
DFSTraverse(G);
cout << endl;
return 0;
}
/* cin.txt:
2
4
5
4
5
3
6
7
7
0
*/


本文介绍了一个使用深度优先搜索(DFS)算法遍历图的C++实现案例。该算法适用于连通图,并通过递归的方式访问每一个顶点。文中详细展示了如何定义邻接矩阵、递归地进行深度优先遍历以及输出遍历过程。
1341

被折叠的 条评论
为什么被折叠?



