//采用鄰接表表示圖的深度優先搜索遍歷
#include <iostream>
using namespace std;
#define MVNum 100
typedef char VerTexType;
typedef char VerTexType;
typedef struct ArcNode {
int adjvex;
struct ArcNode* nextarc;
}ArcNode;
typedef struct VNode {
VerTexType data;
ArcNode* firstarc;
}VNode, AdjList[MVNum];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
bool visited[MVNum];
int LocateVex(ALGraph G, VerTexType v) {
for (int i = 0;i < G.vexnum;++i)
if (G.vertices[i].data == v)
return i;
return -1;
}
void CreateUDG(ALGraph& G) {
int i, k;
cout << "請輸入總頂點數,總邊數,以空格隔開:";
cin >> G.vexnum >> G.arcnum;
cout << endl;
cout << "輸入點的名稱,如a" << endl;
for (i = 0;i < G.vexnum;++i) {
cout << "請輸入第" << (i + 1) << "個點的名稱:";
cin >> G.vertices[i].data;
G.vertices[i].firstarc = NULL;
}
cout << endl;
cout << "輸入邊依附的頂點,如a b" << endl;
for (k = 0;k < G.arcnum;++k) {
VerTexType v1, v2;
int i, j;
cout << "請輸入第" << (k + 1) << "條邊依附的頂點:";
cin >> v1 >> v2;
i = LocateVex(G, v1);
j = LocateVex(G, v2);
ArcNode* p1 = new ArcNode;
p1->adjvex = j;
p1->nextarc = G.vertices[j].firstarc;
G.vertices[j].firstarc = p1;
ArcNode* p2 = new ArcNode;
p1->adjvex = j;
p1->nextarc = G.vertices[j].firstarc;
G.vertices[j].firstarc = p2;
}
}
void DFS(ALGraph G, int v) {
cout << G.vertices[v].data << " ";
visited[v] = true;
ArcNode* p = G.vertices[v].firstarc;
while (p != NULL) {
int w = p->adjvex;
if (!visited[w]) DFS(G, w);
p = p->nextarc;
}
}
int main() {
cout << "采用鄰接表表示圖的深度優先搜索遍歷";
ALGraph G;
CreateUDG(G);
cout << endl;
cout << "無向連通圖G創建完成!" << endl;
cout << "請輸入其實的點";
VerTexType c;
cin >> c;
int i;
for (i = 0;i < G.vexnum;++i) {
if (c == G.vertices[i].data)
break;
}
cout << endl;
while (i >= G.vexnum) {
cout << "該點不存在,請重新輸入!" << endl;
cout << "請輸入遍歷連通圖的起始點:";
cin >> c;
for (i = 0;i < G.vexnum;++i) {
if (c == G.vertices[i].data)
break;
}
}
cout << "深度優先搜索遍歷圖結果:" << endl;
DFS(G, i);
cout << endl;
return 0;
}