[LintCode] Graph Valid Tree
Posted 努橙刷题编
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] Graph Valid Tree相关的知识,希望对你有一定的参考价值。
http://www.lintcode.com/en/problem/graph-valid-tree/
DFS 解法:
public class Solution { /** * @param n an integer * @param edges a list of undirected edges * @return true if it‘s a valid tree, or false */ public boolean validTree(int n, int[][] edges) { // Write your code here if (n <= 0 || edges == null || n - 1 != edges.length) { return false; } int[][] matrix = new int[n][n]; Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < edges.length; i++) { matrix[edges[i][0]][edges[i][1]] = 1; matrix[edges[i][1]][edges[i][0]] = 1; } dfs(matrix, 0, set); return set.size() == n; } private void dfs(int[][] matrix, int start, Set<Integer> set) { if (set.contains(start)) { return; } set.add(start); for (int i = 0; i < matrix.length; i++) { if (matrix[start][i] == 1) { dfs(matrix, i, set); } } } }
Union Find 解法:
public class Solution { /** * @param n an integer * @param edges a list of undirected edges * @return true if it‘s a valid tree, or false */ class UnionFind { int[] id; int[] weight; public UnionFind(int n) { id = new int[n]; weight = new int[n]; for (int i = 0; i < n; i++) { id[i] = i; weight[i] = 1; } } public void union(int i, int j) { int rootI = find(i); int rootJ = find(j); if (weight[rootI] < weight[rootJ]) { id[rootI] = rootJ; weight[rootJ] += weight[rootI]; } else { id[rootJ] = rootI; weight[rootI] += weight[rootJ]; } } public int find(int i) { if (id[i] != i) { return find(id[i]); } return i; } } public boolean validTree(int n, int[][] edges) { if (n <= 0 || edges == null || n - 1 != edges.length) { return false; } UnionFind uf = new UnionFind(n); for (int i = 0; i < edges.length; i++) { if (uf.find(edges[i][0]) == uf.find(edges[i][1])) { return false; } uf.union(edges[i][0], edges[i][1]); } return true; } }
这道题还可以用 BFS 解。
以上是关于[LintCode] Graph Valid Tree的主要内容,如果未能解决你的问题,请参考以下文章
lintcode178- Graph Valid Tree- medium