261. Graph Valid Tree

39 阅读1分钟

image.png

image.png

Solution 1: check if loop exist

class Solution {
    public boolean validTree(int n, int[][] edges) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int i = 0; i < n; i++) {
            graph.put(i, new ArrayList<>());
        }

        for (int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }

        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);
        
        Set<Integer> visited = new HashSet<>();
        visited.add(0);

        Map<Integer, Integer> parent = new HashMap<>();
        parent.put(0, -1);

        while (!queue.isEmpty()) {
            int cur = queue.poll();
            visited.add(cur);
            for (int neighbour : graph.get(cur)) {
                parent.put(neighbour, cur);
                if (parent.get(cur) == neighbour) {
                    continue;
                }
                if (visited.contains(neighbour)) {
                    return false;
                }
                queue.offer(neighbour);
            }
        }
        
        // for unconnected part
        return visited.size() == n;
    }
}

Solution 2: Using graph property

  • Check whether or not there are n - 1 edges. If there's not, then return false.
  • Check whether or not the graph is fully connected. Return true if it is, false if otherwise.
class Solution {
    public boolean validTree(int n, int[][] edges) {
        // satisfies edge requirement?
        if (edges.length != n - 1) {
            return false;
        }

        // build graph
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int i = 0; i < n; i++) {
            graph.put(i, new ArrayList<>());
        }
        // undirected graph
        for (int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }

        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);

        Set<Integer> visited = new HashSet<>();
        visited.add(0);

        // visit graph, make sure it is connected
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            for (int neighbour : graph.get(cur)) {
                if (visited.contains(neighbour)) {
                    continue; // parent OR loop
                }
                visited.add(neighbour);
                queue.offer(neighbour);
            }
        }

        // make sure it's connected
        return visited.size() == n; 
    }
}