xi and Bo(图遍历问题:从创建图到判断图上的两个节点是否能连通)

在这里插入图片描述

Sample Input

3
0 3
3
3 1 2 3
3 4 5 6
3 1 5 6
0 4
2
3 0 2 3
2 2 4
3 2
1
4 2 1 0 3

Sample Output

No
Yes
Yes

Source

中南大学第五届大学生程序设计竞赛-热身赛

Solution

#include <iostream>
#include <cmath>
#include <set>

using namespace std;

//判断图上的两个节点是否连通 
bool can_reach(bool stations[][101],int sta1,int sta2,set<int>& sets){
	if(stations[sta1][sta2]) return true;
	
	sets.insert(sta1);
	for(int i=0; i<101; i++){
		if(stations[sta1][i] && (sets.find(i) == sets.end())){
			if(can_reach(stations,i,sta2,sets)) return true;
		}
	}
	
	return false;
}

int main(int argc, char** argv) {
	int T;
	cin>>T;
	
	for(int i=0; i<T; i++){
		int sta1,sta2;
		cin>>sta1>>sta2;
		
		int n;
		cin>>n;
		bool stations[101][101] = {false};  //图创建 
		for(int j=0; j<n; j++){
			int m;
			cin>>m;
			int temp1,temp2;
			cin>>temp1; 
			for(int k=0; k<m-1; k++){
				cin>>temp2;
				stations[temp1][temp2] = true;
				stations[temp2][temp1] = true;
			}
		}
		set<int> sets; //set容器用来记录是否搜索过该节点 
		if(can_reach(stations,sta1,sta2,sets)){
			cout<<"Yes"<<endl;
		}else{
			cout<<"No"<<endl;
		}
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZenSheep

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值