邻接表实现BFS和DFS C++

 邻接表实现BFS和DFS C++

#include <iostream>
#include<vector>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

struct Edge{
	int to;
	int w;
};
vector<Edge> a[100];
int visit[100];

void dfs(int x) {
	visit[x] = 1;
	cout <<x<< endl;
	for (int i = 0; i < a[x].size(); i++) {
		if (!visit[a[x][i].to]) {
			dfs(a[x][i].to);
		   }
	 }
}

void bfs(int x) {
	queue<int>Q;
	visit[x]=1;
	Q.push(x);
	cout << x << endl;
	while (!Q.empty()) {
		int w = Q.front();

		Q.pop();
		for (int i = 0; i < a[w].size(); i++) {
			if (!visit[a[w][i].to]) {
				visit[a[w][i].to] = 1;
				Q.push(a[w][i].to);
				cout << a[w][i].to << endl;
			}
		}
	}
}

void BFStraverse(int n){
	
	for(int i=1;i<=n;i++){
		if(!visit[i]){
			bfs(i);
		}
	}
	
	
	
}

void DFStraverse(int n){
		for(int i=1;i<=n;i++){
		if(!visit[i]){
			dfs(i);
		}
	}
	
} 



int main()
{
	int n, m;
	cin >> n >> m;
	int x, y, z;
	for (int i = 1; i <= m; i++) {
		cin >> x >> y >> z;
		Edge e;
		e.to = y, e.w = z;
		a[x].push_back(e);
	}

	memset(visit, 0, sizeof(visit));
	//bfs(1);
	//BFStraverse(n);
	DFStraverse(n);
	return 0;
}

测试数据:

9 10
1 2 1
1 3 1
1 4 1
2 5 1
2 6 1
3 6 1
3 7 1
3 8 1
4 8 1
4 9 1
4 9 1
 

BFS 输出结果:

DFS输出结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值