//深度优先搜索遍历连通图的递归算法
#include <iostream>
using namespace std;
#define MVNun 100
typedef char VerTexType;
typedef int ArcType;
typedef struct {
VerTexType vexs[MVNun];
ArcType arcs[MVNun][MVNun];
int vexnum, arcnum;
}Graph;
bool visited[MVNun];
int FirstAdjVex(Graph G, int v);
int NextAdjVex(Graph G, int v, int w);
int LocateVex(Graph G, VerTexType v) {
for (int i = 0;i < G.vexnum;++i) {
if (G.vexs[i] == v)
return i;
}
return -1;
}
void CreateUDN(Graph& G) {
int i, j, k;
cout << "请输入总顶点数,总边数 , 以空格隔开:";
cin >> G.vexnum >> G.arcnum;
cout << endl;
cout << "输入点的名称,如 a:" << endl;
for (i = 0;i < G.vexnum;++i) {
cout << "请输入第" << (i + 1) << "请输入第";
cin >> G.vexs[i];
}
cout << endl;
for (i = 0;i < G.vexnum;++i)
for (j = 0;j < G.vexnum;++j)
G.arcs[i][j] = 0;
cout << "输入边依附的顶点,如:a b" << endl;
for (k = 0;k < G.arcnum;++k) {
VerTexType v1, v2;
cout << "请输入第" << (k + 1) << "条边依附的顶点:";
cin >> v1 >> v2;
i = LocateVex(G, v1);
j = LocateVex(G, v2);
G.arcs[j][i] = G.arcs[i][j] = 1;
}
}
void DFS(Graph G, int v) {
cout << G.vexs[v] << " "; visited[v] = true;
int w;
for (w = FirstAdjVex(G, v); w >= 0; w = NextAdjVex(G, v, w))
if (!visited[w]) DFS(G, w);
}
int FirstAdjVex(Graph G, int v) {
int i;
for (i = 0;i < G.vexnum;++i) {
if (G.arcs[v][i] == 1 && visited[i] == false)
return i;
}
return -1;
}
int NextAdjVex(Graph G, int v, int w) {
int i;
for (i = w;i < G.vexnum;++i) {
if (G.arcs[v][i] == 1 && visited[i] == false)
return i;
}
return -1;
}
int main() {
cout << "深度优先搜索遍历连通图的递归算法";
Graph G;
CreateUDN(G);
cout << endl;
cout << "无向连通图G创建完成!" << endl;
cout << "请输入遍历连通图的起始点:";
VerTexType c;
cin >> c;
int i;
for (i = 0;i < G.vexnum;++i) {
if (c == G.vexs[i])
break;
}
cout << endl;
while (i >= G.vexnum) {
cout << "该点不存在,请重新输入!" << endl;
cout << "请输入遍历连通图的起始点:";
cin >> c;
for (i = 0;i < G.vexnum;++i) {
if (c == G.vexs[i]) {
break;
}
}
}
cout << "深度优先搜索遍历连通图结果:" << endl;
DFS(G, i);
cout << endl;
return 0;
}