题目链接:寻找存在的路径
本题是要寻找无向图是否存在从 s 到 t 的一条路径,那么选择从 s 出发,进行深度搜索,只要能到达 t ,就说明存在路径。
#include <bits/stdc++.h>
using namespace std;
bool flag = false;
void dfs(vector<list<int>>& graph, vector<bool>& visited, int s, int t){
if(visited[s]){
return;
}
visited[s] = true;
if(s == t){
flag = true;
}
for(auto& cur : graph[s]){
dfs(graph, visited, cur, t);
}
}
int main(){
int n,m,s,t;
cin >> n >> m;
vector<list<int>> graph(n + 1);
while(m--){
cin >> s >> t;
graph[s].push_back(t);
graph[t].push_back(s);
}
cin >> s >> t;
vector<bool> visited(n + 1, false);
dfs(graph, visited, s, t);
if(flag){
cout << 1 << endl;
}else{
cout << 0 << endl;
}
return 0;
}
本题同样可以使用 并查集 来完成
#include <bits/stdc++.h>
using namespace std;
void init(vector<int>& father){
for(int i = 0; i < father.size(); i++){
father[i] = i;
}
}
int find(vector<int>& father, int t){
return t == father[t] ? t : father[t] = find(father, father[t]);
}
bool isSame(vector<int>& father, int u, int v){
u = find(father, u);
v = find(father, v);
return u == v;
}
void join(vector<int>& father, int u, int v){
u = find(father, u);
v = find(father, v);
if(u == v){
return;
}
father[v] = u;
}
int main(){
int n,m,s,t;
cin >> n >> m;
vector<int> father(n + 1);
vector<list<int>> graph(n + 1);
init(father);
while(m--){
cin >> s >> t;
graph[s].push_back(t);
}
cin >> s >> t;
for(int i = 1; i < graph.size(); i++){
for(auto& j : graph[i]){
join(father, i, j);
}
}
if(isSame(father, s, t)){
cout << 1 << endl;
}else{
cout << 0 << endl;
}
return 0;
}