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.
For example:
Given
Show Hint 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
.public class Solution {
public boolean validTree(int n, int[][] edges) {
if (n <= 0) return false;
HashMap<Integer, HashSet<Integer>> edgeMap = new HashMap<>();
for (int[] edge : edges) {
int v1 = edge[0];
int v2 = edge[1];
HashSet<Integer> set1 = edgeMap.get(v1);
if (set1 == null) {
set1 = new HashSet<Integer>();
edgeMap.put(v1, set1);
}
set1.add(v2);
HashSet<Integer> set2 = edgeMap.get(v2);
if (set2 == null) {
set2 = new HashSet<Integer>();
edgeMap.put(v2, set2);
}
set2.add(v1);
}
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(0);
int count = 0;
boolean visited[] = new boolean[n];
while (!queue.isEmpty()) {
int v = queue.pop();
if (visited[v]) return false;
count++;
visited[v] = true;
HashSet<Integer> nextVs = edgeMap.get(v);
if (nextVs != null) {
for (int next : nextVs) {
queue.add(next);
edgeMap.get(next).remove(v);
}
}
}
return count == n;
}
}
=====
public class Solution {
public boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) {
return false;
}
int nums[] = new int[n];
Arrays.fill(nums, -1);
for (int edge[] : edges) {
int x = find(nums, edge[0]);
int y = find(nums, edge[1]);
if (x == y) return false;
//nums[x] = y;
nums[y] =x;
}
return edges.length == n - 1;
}
private int find(int[] nums, int x) {
if (nums[x] == -1) {
return x;
}
return find(nums, nums[x]);
}
}
没有评论:
发表评论