//深度优先搜索遍历非连通图
#include <iostream>
using namespace std;
#define MVNum 100
typedef char VerTexType;
typedef int ArcType;
typedef struct {
VerTexType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum, arcnum;
}Graph;
bool visited[MVNum];
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);
}
//key
void DFSTraverse(Graph G) {
int v;
for (v = 0;v < G.vexnum;++v)
visited[v] = false;
for (v = 0;v < G.vexnum;++v)
if (!visited[v]) DFS(G, v);
}
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 << "深度优先搜索遍历非连通图结果:" << endl;
DFSTraverse(G);
cout << endl;
return 0;
}