基于邻接表的深度优先遍历
#include<iostream>
#include<stack>
using namespace std;
#define maxsize 100
typedef struct ArcNode {
int val;
ArcNode* next;
ArcNode() :val(0), next(nullptr){}
ArcNode(int x):val(x),next(nullptr){}
}ArcNode;
typedef struct VexNode {
int data;
ArcNode* first;
VexNode():data(0),first(nullptr){}
}VexNode;
typedef struct {
VexNode vexs[maxsize];
int VexNum; int ArcNum;
}ALGraph;
void CreateGraph(ALGraph& G, int n, int m) {
G.VexNum = n;
G.ArcNum = m;
for (int i = 1; i <= n; i++) {
G.vexs[i].data = i;
}
for (int i = 1; i <= m; i++) {
int a1, a2;
cin >> a1 >> a2;
ArcNode* p1 = new ArcNode(a1);
ArcNode* p2 = new ArcNode(a2);
p1->next = G.vexs[a2].first;
G.vexs[a2].first = p1;
p2->next = G.vexs[a1].first;
G.vexs[a1].first = p2;
}
}
//非递归dfs 使用栈
//这回就将编号和数值绑定了,简化一下
void dfs(ALGraph G,int start) {
int visited[30] = { 0 };
stack<int>s; //递归栈
visited[start] = 1;
s.push(start);
cout << start;
s.pop();
ArcNode* p = G.vexs[start].first;
while (p) {
if (visited[p->val] == 0) {
visited[p->val] = 1;
s.push(p->val);
}
p = p->next;
}
while (!s.empty()) {
int top = s.top();
cout << " " << top;
s.pop();
//遍历top的邻接表
ArcNode* p = G.vexs[top].first;
while (p) {
if (visited[p->val] == 0) {
visited[p->val] = 1;
s.push(p->val);
}
p = p->next;
}
}
cout << endl;
}
void print(ALGraph& G) {
for (int i = 1; i <= G.VexNum; i++) {
cout << G.vexs[i].data;
ArcNode* p = G.vexs[i].first;
while (p) {
cout << " " << p->val;
p = p->next;
}
cout << endl;
}
}
int main() {
int n, m;
while (cin >> n >> m && (n != 0 && m != 0)) {
ALGraph G;
CreateGraph(G, n, m);
int start;
cin >> start;
dfs(G, start);
/* print(G);*/
}
return 0;
}