BJFUOJ-282

基于邻接表的深度优先遍历

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值