- Graph Valid Tree
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Example
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Notice
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
**注意:图是树需要满足3个条件
- 连通性:从任意一个节点出发可以都搜索到另外任意一个节点。
- 边数 = 点数 - 1
- 没有环。
数学可以证明,上面任意两个条件可以推出第三个。也就是说,上面满足任意两个条件的话,图就是树。**
思路:并查集
注意:
- 无向图的点数=边数+1。所以如果输入的点数!=边数+1,直接返回false。
- 最后连通块数目应该是1,否则就不能叫图了。所以最后判断count==1即可。
代码如下:
class Solution {
public:
/**
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
bool validTree(int n, vector<vector<int>> &edges) {
int m = edges.size();
if (n != m + 1) return false; //这行重要,如果是连通图,但是有环。这行会发现。
count = n;
father.resize(n);
for (int i = 0; i < n; ++i) {
father[i] = i;
}
for (int i = 0; i < m; ++i) {
collect(edges[i][0], edges[i][1]);
}
return count == 1;
}
private:
vector<int> father;
int count;
int find(int k) {
if (father[k] == k) return k;
//path compression
return father[k] = find(father[k]);
}
void collect(int a, int b) {
int fatherA = find(a);
int fatherB = find(b);
if (fatherA != fatherB) {
father[fatherA] = fatherB;
count--;
}
}
};
解法2:BFS。
注意:如果有环的话,在 if (edges.size() != n - 1) return false; 这里就会返回false。
class Solution {
public:
/**
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
bool validTree(int n, vector<vector<int>> &edges) {
if (edges.size() == 0) return n == 1;
if (edges.size() != n - 1) return false;
vector<vector<int>> nodes(n);
for (auto edge : edges) {
nodes[edge[0]].push_back(edge[1]);
nodes[edge[1]].push_back(edge[0]);
}
unordered_set<int> visited;
queue<int> q;
q.push(0);
visited.insert(0);
while (!q.empty()) {
auto frontNode = q.front();
q.pop();
if (nodes[frontNode].size() > 0)
for (auto node : nodes[frontNode]) {
if (visited.find(node) == visited.end()) {
q.push(node);
visited.insert(node);
}
}
}
return visited.size() == n;
}
};