261. 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.

For 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.

Note: 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.

避免回访前驱:
recursive方式:传进parent来判断是不是nextNeighbor != parent?
stack:push的时候也push parent

Solution1:DFS recursive 找global && 所有vertices相连

思路:DFS 看global上是否不存在cycle && 并且所有vertices都是相连的
区别于207. Course Schedule http://www.jianshu.com/p/8665248b4458 onpath上cycle
写法1_a: 递归内部置visited=true
写法1_b: 在递归前置visited=true
Time Complexity: O(E+V) Space Complexity: O(E+V)

Solution2:similar to solution3

Time Complexity: O(E+V) Space Complexity: O(E+V)

Solution3:DFS(stack) 看global上是否不存在cycle

All same with solution2, just replace queue with stack
思路:DFS 看global上是否不存在cycle(通过检查是否visited过,但要避免check前驱, push的时候也push parent,来判断是不是nextNeighbor != parent )

3_b: 内部置visited=true

Time Complexity: O(E+V) Space Complexity: O(E+V)

Solution4:Union Find 看global上是否不存在cycle

思路: 根据给每个边,每个结点都assign不同的id,union相连的,如果碰到有相同的id,说明有cycle。因为只在给的边上做,没有边的isolated结点 检查可以用edges.length == n - 1判断是否存在单独isolated的结点。而solution1-3不可以用此判断,因为不一定检查到所有的边,只能检查某块edge,这样就可能出现先单独结点dfs/bfs成功,但是也满足edges.length == n - 1,但其实别的块有loop。
实现4b: 高票简版
Time Complexity: O(ElogV) ? Space Complexity: O(V) ?

Solution1a Code:

class Solution {
    public boolean validTree(int n, int[][] edges) {
        // init graph (adjList)
        List> adjList = new ArrayList>(n);
        for (int i = 0; i < n; i++)
            adjList.add(i, new ArrayList());
        // add edges    
        for (int i = 0; i < edges.length; i++) {
            int u = edges[i][0], v = edges[i][1];
            adjList.get(u).add(v);
            adjList.get(v).add(u);
        }
        
        
        boolean[] visited = new boolean[n];
        visited[0] = true;
        // make sure there's no cycle
        if (dfsCycle(adjList, 0, visited, -1)) {
            return false;
        }
        
        // check if all nodes are connected
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                return false;
            }
        }
        
        return true;
    }
    
    // dfs checking if there is cycle
    boolean dfsCycle(List> adjList, int cur, boolean[] visited, int prev) {
        visited[cur] = true;
        
        for (int i = 0; i < adjList.get(cur).size(); i++) {
            int neighbor = adjList.get(cur).get(i);

            if (neighbor == prev) {
                continue;
            }
            else if (visited[neighbor]) {
                return true;
            }
            else {
                if (dfsCycle(adjList, neighbor, visited, cur)) {
                    return true;
                }
            }
        }
        
        return false;
    }
}

Solution1b Code:

class Solution {
    public boolean validTree(int n, int[][] edges) {
        // init graph (adjList)
        List> adjList = new ArrayList>(n);
        for (int i = 0; i < n; i++)
            adjList.add(i, new ArrayList());
        // add edges    
        for (int i = 0; i < edges.length; i++) {
            int u = edges[i][0], v = edges[i][1];
            adjList.get(u).add(v);
            adjList.get(v).add(u);
        }
        
        
        boolean[] visited = new boolean[n];
        visited[0] = true;
        // make sure there's no cycle
        if (dfsCycle(adjList, 0, visited, -1)) {
            return false;
        }
        
        // check if all nodes are connected
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                return false;
            }
        }
        
        return true;
    }
    
    // dfs checking if there is cycle
    boolean dfsCycle(List> adjList, int cur, boolean[] visited, int prev) {
        for (int i = 0; i < adjList.get(cur).size(); i++) {
            int neighbor = adjList.get(cur).get(i);

            if (neighbor == prev) {
                continue;
            }
            else if (visited[neighbor]) {
                return true;
            }
            else {
                visited[neighbor] = true;
                if (dfsCycle(adjList, neighbor, visited, cur)) {
                    return true;
                }
            }
        }
        
        return false;
    }
}

Solution2 Code:

TODO

Solution3 Code:

class Solution {
    private class NodeWithParent {
        int id;
        int parentId;
        
        public NodeWithParent(int id, int parentId) {
            this.id = id;
            this.parentId = parentId;
        }
    }
    
    public boolean validTree(int n, int[][] edges) {
        // init graph (adjList)
        List> adjList = new ArrayList>(n);
        for (int i = 0; i < n; i++)
            adjList.add(i, new ArrayList());
        for (int i = 0; i < edges.length; i++) {
            int u = edges[i][0], v = edges[i][1];
            adjList.get(u).add(v);
            adjList.get(v).add(u);
        }
        
        // dfs
        boolean[] visited = new boolean[n]; 
        
        Deque stack = new ArrayDeque();
        stack.push(new NodeWithParent(0, -1));
        visited[0] = true;
        
        while (!stack.isEmpty()) {
            NodeWithParent cur = stack.pop();
            for (int neighborId: adjList.get(cur.id)) {
                if (neighborId == cur.parentId) {
                    continue;
                }
                else if ((visited[neighborId])) {
                    return false;
                }
                else {
                    stack.push(new NodeWithParent(neighborId, cur.id));
                    visited[neighborId] = true;
                }
            }
        }
        
        // check if all nodes are connected
        for (int i = 0; i < n; i++) {
            if (!visited[i]) 
                return false;
        }
        return true;
    }
}

Solution3_b Code:

class Solution {
    private class NodeWithParent {
        int id;
        int parentId;
        
        public NodeWithParent(int id, int parentId) {
            this.id = id;
            this.parentId = parentId;
        }
    }
    
    public boolean validTree(int n, int[][] edges) {
        // init graph (adjList)
        List> adjList = new ArrayList>(n);
        for (int i = 0; i < n; i++)
            adjList.add(i, new ArrayList());
        for (int i = 0; i < edges.length; i++) {
            int u = edges[i][0], v = edges[i][1];
            adjList.get(u).add(v);
            adjList.get(v).add(u);
        }
        
        // dfs
        boolean[] visited = new boolean[n]; 
        
        Deque stack = new ArrayDeque();
        stack.push(new NodeWithParent(0, -1));
        visited[0] = true;
        
        while (!stack.isEmpty()) {
            NodeWithParent cur = stack.pop();
            visited[cur.id] = true;
            for (int neighborId: adjList.get(cur.id)) {
                if (neighborId == cur.parentId) {
                    continue;
                }
                else if ((visited[neighborId])) {
                    return false;
                }
                else {
                    stack.push(new NodeWithParent(neighborId, cur.id));
                }
            }
        }
        
        // check if all nodes are connected
        for (int i = 0; i < n; i++) {
            if (!visited[i]) 
                return false;
        }
        return true;
    }
}

Solution4_a Code:

class Solution {
    
    class UF {
        private int[] id;  
        private int[] sz;  // for an id, the number of elements in that id
        private int count; // number of sort of id

        public UF(int n) {
            
            this.id = new int[n];
            this.sz = new int[n];
            this.count = 0;
            
            // init
            for (int i = 0; i < n; i++) {
                this.id[i] = i;
                this.sz[i] = 1;
                this.count++;
            }
        }

        public void union(int p, int q) {
            int p_root = find(p), q_root = find(q);
            // weighted quick union
            ///*
            if(p_root == q_root) return;
            if (sz[p_root] < sz[q_root]) { 
                id[p_root] = q_root; sz[q_root] += sz[p_root];
            } else {
                id[q_root] = p_root; sz[p_root] += sz[q_root];
            }
            --count;
            //*/
            
            // regular
            /*
            if(p_root == q_root) return;
            id[p_root] = q_root;
            --count;
            */
        }

        public int find(int i) { // path compression
            for (;i != id[i]; i = id[i])
                id[i] = id[id[i]]; 
            return i;
        }

        public boolean connected(int p, int q) {
            int p_root = find(p);
            int q_root = find(q);
            if(p_root != q_root) return false;
            else return true;
        }

        public int count() { 
            return this.count; 
        }
        
    }
    
    public boolean validTree(int n, int[][] edges) {
        UF uf = new UF(n);
        
        // perform union find
        for (int i = 0; i < edges.length; i++) {
            int x = uf.find(edges[i][0]);
            int y = uf.find(edges[i][1]);
            // if two vertices happen to be in the same set
            // then there's a cycle
            if (x == y) return false;
            else {
                // union
                uf.union(x, y);
            }
        }
        
        return edges.length == n - 1;
    }
}

Solution4_b Code:

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        // initialize n isolated islands
        int[] nums = new int[n];
        Arrays.fill(nums, -1);
        
        // perform union find
        for (int i = 0; i < edges.length; i++) {
            int x = find(nums, edges[i][0]);
            int y = find(nums, edges[i][1]);
            
            // if two vertices happen to be in the same set
            // then there's a cycle
            if (x == y) return false;
            
            // union
            nums[x] = y;
        }
        
        return edges.length == n - 1;
    }
    
    int find(int nums[], int i) {
        if (nums[i] == -1) return i;
        return find(nums, nums[i]);
    }
}

你可能感兴趣的:(261. Graph Valid Tree)