1. 程式人生 > >LintCode178 圖是否是樹

LintCode178 圖是否是樹

  1. 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.
一棵樹必須具備如下特性:

(1)是一個全連通圖(所有節點相通)

(2)無迴路

其中(2)等價於:(3)圖的邊數=節點數-1

因此我們可以利用特性(1)(2)或者(1)(3)來判斷。
圖的構建方式:HashMap<Integer,HashSet> graph = new HashMap<>(); 用map儲存節點和相鄰節點

public boolean validTree(int n, int[][] edges) {
        // write your code here
        if(n == 0 || edges.length != n - 1) return false;
        HashMap<Integer,HashSet<Integer>> graph = initGraph(n,edges);
        Queue<Integer> queue = new LinkedList<>();
        HashSet<Integer> hash = new HashSet<>();
        queue.offer(0);
        hash.add(0);
        while(!queue.isEmpty()){
            int node = queue.poll();
            for(int neighbor : graph.get(node)){
                if(hash.contains(neighbor)){
                    continue;
                }
                queue.offer(neighbor);
                hash.add(neighbor);
            }
        }
        return hash.size() == n;
    }
    
    private HashMap initGraph(int n, int[][] edges){
        HashMap<Integer,HashSet<Integer>> graph = new HashMap<>();
        for(int i = 0; i < n; i++){
            graph.put(i, new HashSet<Integer>());
        }
        for(int i = 0; i < edges.length; i++){
            int u = edges[i][0];
            int v = edges[i][1];
            graph.get(u).add(v);
            graph.get(v).add(u);
        }
        return graph;
    }