Last active
September 28, 2017 21:44
-
-
Save BiruLyu/fbb0350f62b7d1d6c7e84edb00f3f3a9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public boolean canFinish(int numCourses, int[][] prerequisites) { | |
| if (prerequisites == null || prerequisites.length < 1 || prerequisites[0].length < 1) return true; | |
| List<List<Integer>> adj = new ArrayList<>(); | |
| int[] indegree = new int[numCourses]; | |
| for (int i = 0; i < numCourses; i++) { | |
| adj.add(new ArrayList<>()); | |
| } | |
| for (int[] e : prerequisites) { | |
| adj.get(e[0]).add(e[1]); | |
| indegree[e[1]]++; | |
| } | |
| Queue<Integer> q = new LinkedList<>(); | |
| for (int i = 0; i < numCourses; i++) { | |
| if (indegree[i] == 0) { | |
| q.add(i); | |
| } | |
| } | |
| int cnt = 0; | |
| while (!q.isEmpty()) { | |
| int cur = q.poll(); | |
| cnt++; | |
| for (int next : adj.get(cur)) { | |
| if (--indegree[next] == 0) { | |
| q.offer(next); | |
| } | |
| } | |
| } | |
| return cnt == numCourses; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| public boolean canFinish(int numCourses, int[][] prerequisites) { | |
| List<List<Integer>> adjList = new ArrayList<List<Integer>>(); | |
| for(int i = 0; i < numCourses; i++){ | |
| adjList.add(new ArrayList<Integer>()); | |
| } | |
| for(int i = 0; i < prerequisites.length; i++){ | |
| int start = prerequisites[i][0]; | |
| int end = prerequisites[i][1]; | |
| adjList.get(start).add(end); | |
| } | |
| int[] explored = new int[numCourses]; | |
| for(int i = 0; i < numCourses; i++){ | |
| if(explored[i] == 2){//优化!!! | |
| continue; | |
| } | |
| if(hasCycle(adjList, explored, i)){ | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| public boolean hasCycle(List<List<Integer>> adjList, int[] explored, int cur){ | |
| explored[cur] = 1; | |
| for(int i = 0; i < adjList.get(cur).size(); i++){ | |
| int temp = adjList.get(cur).get(i); | |
| if (explored[temp] == 1) { | |
| return true; | |
| } else if (explored[temp] == 0) { | |
| if (hasCycle(adjList, explored, temp)) { | |
| return true; | |
| } | |
| } | |
| } | |
| explored[cur] = 2; | |
| return false; | |
| } | |
| } | |
| /* | |
| 2 | |
| [[1,0]] | |
| 2 | |
| [[1,0],[0,1]] | |
| 5 | |
| [[0,1],[1,2],[1,3],[1,4],[2,3]] | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment