思路
并查集
代码
cpp
class Solution {
private:
int n = 200005;
int father[200005] = {0};
void init()
{
int i;
for(i = 0; i < n; i++)
{
father[i] = i;
}
}
int find(int u)
{
if(u == father[u])
{
return u;
}
else
{
return father[u] = find(father[u]);
}
}
bool isSame(int u, int v)
{
u = find(u);
v = find(v);
return u == v;
}
// 加入 u -> v
void join(int u, int v)
{
u = find(u);
v = find(v);
if(u == v)
{
return;
}
else
{
father[u] = v;
}
}
public:
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
int i, u, v;
init();
for(i = 0; i < edges.size(); i++)
{
join(edges[i][0], edges[i][1]);
}
return isSame(source, destination);
}
};
注意数组不要越界了,validPath
函数里n
是节点个数,edge
长度是边的个数,可不一定相等哦!