算法6.6 采用邻接表表示图的深度优先搜索遍历
代码实现
#pragma once
#include <iostream>
using namespace std;
#define MVNum 100
typedef int OtherInfo;
typedef char VerTexType;
typedef struct ArcNode
{
int adjvex;
struct ArcNode* nextarc;
OtherInfo info;
}ArcNode;
typedef struct VexNode
{
VerTexType data;
ArcNode* firstarc;
}VexNode, AdjList[MVNum];
typedef struct
{
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
int LocateVex(ALGraph G, VerTexType v)
{
for (int i = 0; i < G.vexnum; i++)
{
if (v == G.vertices[i].data)
{
return i;
}
}
}
void CreateUDG(ALGraph& G)
{
cout << "请输总顶点数:";
cin >> G.vexnum;
cout << "请输总边数:";
cin >> G.arcnum;
for (int i = 0; i < G.vexnum; i++)
{
cout << "输入顶点"<<i<<": ";
cin >> G.vertices[i].data;
G.vertices[i].firstarc = NULL;
}
VerTexType v1, v2;
ArcNode* p1;
ArcNode* p2;
for (int k = 0; k < G.arcnum; k++)
{
cout << "输入一条边依附的两个顶点:";
cin >> v1 >> v2;
int i = LocateVex(G, v1);
int j = LocateVex(G, v2);
p1 = new ArcNode;
p1->adjvex = j;
p1->nextarc = G.vertices[i].firstarc;
G.vertices[i].firstarc = p1;
p2 = new ArcNode;
p2->adjvex = i;
p2->nextarc = G.vertices[j].firstarc;
G.vertices[j].firstarc = p2;
}
}
void ShowGraph(ALGraph G)
{
for (int i = 0; i < G.vexnum; i++)
{
cout << G.vertices[i].data << " ";
ArcNode* temp = G.vertices[i].firstarc;
while (temp!= NULL)
{
cout << temp->adjvex << " ";
temp = temp->nextarc;
}
cout << endl;
}
}
bool visited[MVNum];
void DFS_AL(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_AL(G, w);
}
p = p->nextarc;
}
}
int main()
{
ALGraph G;
CreateUDG(G);
ShowGraph(G);
for (int i = 0; i < G.vexnum; i++)
{
visited[i] = false;
}
cout << "从哪个顶点开始DFS?" << endl;
int v;
cin >> v;
DFS_AL(G, v-1);
cout << endl;
system("pause");
return 0;
}
运行结果