码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Graph Valid Tree

时间:2017-05-25 01:16:02      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:null   blank   find   roo   return   contain   private   direct   http   

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

标签:null   blank   find   roo   return   contain   private   direct   http   

原文地址:http://www.cnblogs.com/chencode/p/graph-valid-tree.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!