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. Example 1: Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]] Output: true Example 2: Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]] Output: false Three states: visiting , visited, unexpolored In number : 1. 2 0 If visiting node’s nei is also visiting , then cycle class Solution{ public boolean validTree(int n, int[][] edges){ List<List<Integer>> list = new ArrayList<>(); Queue<Integer> queue = new LinkedList<>(); int[] visited = new int[n]; // default inital value is 0, means unexplored for(int i = 0; i < n; i++){ list.add(new ArrayList<>()); } for(int i = 0; i < edges.length; i++){ int firstNode = edges[i][0]; int secNode = edges[i][1]; list.get(firstNode).add(secNode); list.get(secNode).add(firstNode); } queue.offer(0); while(!queue.isEmpty()){ int cur = queue.poll(); visited[cur] = 1; // means visiting for(Integer nei : list.get(cur)){ if(visited[nei] == 1){ return false; } if(visited[nei] == 0){ visited[nei] = 1; queue.offer(nei); } } visited[cur] = 2; // means visited } // another check for valid tree , is it has only one connected component // if no cycle, after all the nodes should be visited, which is 2 in the int[] visited // if there's still nodes left that is not 2, or, in other words, if its 0, // then we know we have more than one connected components for(int i = 0; i < n; i++){ if(visited[i] == 0){ return false; } } return true; } }
posted on 2018-11-06 09:41 猪猪🐷 阅读(84) 评论(0) 收藏 举报
浙公网安备 33010602011771号