There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Example 1:
**Input:** numCourses = 2, prerequisites = [[1,0]]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
**Input:** numCourses = 2, prerequisites = [[1,0],[0,1]]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Constraints:
1 <= numCourses <= 105
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= ai, bi < numCourses
All the pairs prerequisites[i] are unique.
ac1: Topological + BFS
classSolution {publicbooleancanFinish(int numCourses,int[][] prerequisites) {if (numCourses <=0) returnfalse;// have a graphList<List<Integer>> adjList =newArrayList<List<Integer>>();for (int i =0; i < numCourses; i++) {adjList.add(newArrayList<Integer>()); }// get indegreeint[] indegree =newint[numCourses];for (int[] pre : prerequisites) { indegree[pre[0]]++;adjList.get(pre[1]).add(pre[0]); }// BFSQueue<Integer> q =newLinkedList<Integer>();for (int i =0; i <indegree.length; i++) {if (indegree[i] ==0) q.offer(i); }while (!q.isEmpty()) {int head =q.poll();for (int next :adjList.get(head)) { indegree[next]--;if (indegree[next] ==0) {q.offer(next); } } }// Determinefor (int inde : indegree) {if (inde !=0) returnfalse; }returntrue; }}
ac2: Graph + DFS
spend too much time
classSolution {privateboolean[] onStack;privateSet<Integer> visited;publicbooleancanFinish(int numCourses,int[][] prerequisites) {if (numCourses <=0) returnfalse;// have a graphList<List<Integer>> adjList =newArrayList<List<Integer>>(); onStack =newboolean[numCourses]; visited =newHashSet<Integer>();for (int i =0; i < numCourses; i++) {adjList.add(newArrayList<Integer>()); }for (int[] pre : prerequisites) {adjList.get(pre[1]).add(pre[0]); }for (int i =0; i < numCourses; i++) {if (!visited.contains(i) &&hasCycle(adjList, i)) returnfalse; }returntrue; }privatebooleanhasCycle(List<List<Integer>> adjList,int s) {visited.add(s); onStack[s] =true;for (int w :adjList.get(s)) {if (onStack[w] ||hasCycle(adjList,w)) returntrue; } onStack[s] =false;returnfalse; }}