There are a total of n courses you have to take, labeled from 0
to n - 1
.
Some courses may have prerequisites, for example to take course 0 you
have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example
Example 1:
Input: n = 2, prerequisites = [[1,0]]
Output: [0,1]
Example 2:
Input: n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
分析:这里要注意一门课有好几门先修课的情况。
试了下面这种做法,对每一个课程求出所有的先修课。没想到Memory Limit Exceeded!!
public class Solution { /* * @param numCourses: a total of n courses * @param prerequisites: a list of prerequisite pairs * @return: the course order */ public int[] findOrder(int numCourses, int[][] prerequisites) { // 有好几门先修课 Map<Integer, Set<Integer>> map = new HashMap<>(); for (int i = 0; i < numCourses; i++) { map.put(i, new HashSet<>()); } for (int i = 0; i < prerequisites.length; i++) { map.get(prerequisites[i][0]).add(prerequisites[i][1]); } System.out.println(map); int[] res = new int[numCourses]; int level = 0; boolean[] visited = new boolean[numCourses]; for (int i = 0; i < numCourses; i++) { if (visited[i]) { continue; } if (map.get(i).size() == 0) { res[level++] = i; visited[i] = true; continue; } Set<Integer> set = new HashSet<>(); Queue<Integer> q = new LinkedList<Integer>(); Stack<Integer> l = new Stack<>(); q.offer(i); set.add(i); while(q.size() != 0) { int curr = q.poll(); l.push(curr); for (Integer ii: map.get(curr)) { if (set.contains(ii)) { return new int[0]; } if (!visited[ii]) { q.offer(ii); } } } while (l.size() != 0) { int curr = l.pop(); res[level++] = curr; visited[curr] = true; } } if (level < numCourses) { return new int[0]; } else { return res; } } }
没办法,只能参考网上大神的做法。原来只要用一个Queue就可以实现。这里的重点是构建图,把一门课的后修课list(修完这门课后,可以修那修课了)记录下来,他们就是有向图的边,同时记录修这门课要先修几门课,当先修课的数目为0时,就可以修这门课了(也就是可以push到queue里)。
public class Solution { /* * @param numCourses: a total of n courses * @param prerequisites: a list of prerequisite pairs * @return: the course order */ public int[] findOrder(int numCourses, int[][] prerequisites) { int[] needed = new int[numCourses]; List<List<Integer>> reverse = new ArrayList<>(); int[] res = new int[numCourses]; int level = 0; for (int i = 0; i < numCourses; i++){ reverse.add(new ArrayList<Integer>()); } for (int i = 0; i < prerequisites.length; i++) { needed[prerequisites[i][0]]++; reverse.get(prerequisites[i][1]).add(prerequisites[i][0]); } Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < numCourses; i++) { if (needed[i] == 0) { q.offer(i); } } while (q.size() != 0) { int curr = q.poll(); res[level++] = curr; for (int i:reverse.get(curr)) { needed[i]--; if (needed[i] == 0) { q.offer(i); } } } if (level == numCourses) { return res; } else { return new int[0]; } } }