261. Graph Valid Tree
0 ----- 3
|\
| \
| \
1 2
|
40---1--2
/\/
|/\
3 4Previous323. Number of Connected Components in an Undirected GraphNext947. Most Stones Removed with Same Row or Column
Last updated
Was this helpful?
0 ----- 3
|\
| \
| \
1 2
|
40---1--2
/\/
|/\
3 4Last updated
Was this helpful?
Was this helpful?
class Solution {
public:
bool validTree(int n, vector<pair<int, int>>& edges) {
int m = edges.size();
if(n < 1 || edges.size()!= n - 1) return false;
int roots[n];
fill_n(roots, n, -1);
for(pair<int,int> p: edges){
int roota = find(roots, p.first);
int rootb = find(roots, p.second);
// cycle detection
if(roota == rootb) return false;
roots[roota] = rootb;
}
return true;
}
int find ( int roots [], int v){
while(roots[v] != -1) v = roots[v];
return v;
}
};