【leetcode1971】寻找图中是否存在路径
并查集
目录
bfs超时
class Solution {
public:
vector<vector<bool>> graph;
vector<bool> visited;
bool flag;
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
visited.assign(n,0);
graph.assign(n,visited);
for(int i=0;i<n;i++){
graph[i][i]=1;
}
for(int i=0;i<edges.size();i++){
graph[edges[i][0]][edges[i][1]]=1;
graph[edges[i][1]][edges[i][0]]=1;
}
bfs(n,destination,source);
return flag;
}
void bfs(int n, int destination, int node){
if(node==destination){
flag=1;
return;
}
if(graph[node][destination]){
flag=1;
return;
}
visited[node]=1;
for(int i=0;i<n;i++){
if(flag) break;
if(graph[node][i] && !visited[i]){
bfs(n,destination,i);
}
}
}
};
并查集通过
class Solution {
public:
vector<int> fa,rank;
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
for(int i=0;i<n;i++){
fa.push_back(i);
rank.push_back(1);
}
for(int i=0;i<edges.size();i++){
merge(edges[i][0],edges[i][1]);
}
return find(source)==find(destination);
}
int find(int i){
if(fa[i]==i) return i;
else
{
fa[i]=find(fa[i]);
return fa[i];
}
}
void merge(int i,int j){
int x=find(i),y=find(j);
if(rank[x]<=rank[y]) fa[x]=y;
else fa[y]=x;
if (rank[x] == rank[y] && x != y) rank[y]++;
}
};