261. Graph Valid Tree
// means there is a circle in this graph, so it's not a tree
if (x == y) return false;
class Solution {
public boolean validTree(int n, int[][] edges) {
// edge false case => edges.length != n - 1
// union find to check node's parent, if the point (x, y) has the same root
// it means there is a circle in this graph, so it's not a tree
if (n < 1 || edges == null || edges.length != n - 1) return false;
int roots[] = new int[n];
for (int i = 0; i < n; i++) {
roots[i] = -1;
}
for (int pair[] : edges) {
int x = find(roots, pair[0]);
int y = find(roots, pair[1]);
if (x == y) return false;
roots[x] = y;
}
return true;
}
// find ⇒ 只要有父親,就會一路往上找, 直到找到 root, 最後找到底了, 就會回傳根節點
private int find(int roots[], int i) {
while(roots[i] != -1) {
i = roots[i];
}
return i;
}
}with template
Previous2316. Count Unreachable Pairs of Nodes in an Undirected GraphNext323. Number of Connected Components in an Undirected Graph
Last updated