【LeetCode】207. Course Schedule 课程表(Medium)(JAVA)
题目地址: https://leetcode.com/problems/course-schedule/
题目描述:
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-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, is it possible for you to finish all courses?
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:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
- 1 <= numCourses <= 10^5
题目大意
你这个学期必须选修 numCourse 门课程,记为 0 到 numCourse-1 。
在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们:[0,1]
给定课程总量以及它们的先决条件,请你判断是否可能完成所有课程的学习?
提示:
- 输入的先决条件是由 边缘列表 表示的图形,而不是 邻接矩阵 。详情请参见图的表示法。
- 你可以假定输入的先决条件中没有重复的边。
- 1 <= numCourses <= 10^5
解题方法
- 用一个 map 把当前课程预先要完成的课程存起来,因为可能预先要修多个课程,所有 value 是 list 的形式
- 然后要循环判断每个课程是否有陷入循环当中
- 用一个 set 来记录当前路径已经走过的课程,如果再次遇到就说明已经遍历过了,陷入了循环
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (numCourses <= 1) return true;
Map<Integer, List<Integer>> map = new HashMap<>();
Set<Integer> set = new HashSet<>();
boolean[] check = new boolean[numCourses];
for (int i = 0; i < prerequisites.length; i++) {
List<Integer> list = map.get(prerequisites[i][0]);
if (list == null) {
list = new ArrayList<>();
map.put(prerequisites[i][0], list);
}
list.add(prerequisites[i][1]);
}
for (int i = 0; i < numCourses; i++) {
if (check[i]) continue;
if (!cH(map, check, set, i)) return false;
}
return true;
}
public boolean cH(Map<Integer, List<Integer>> map, boolean[] check, Set<Integer> set, int start) {
if (set.contains(start)) return false;
if (check[start]) return true;
check[start] = true;
set.add(start);
List<Integer> list = map.get(start);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
if (!cH(map, check, set, list.get(i))) return false;
}
}
set.remove(start);
return true;
}
}
执行耗时:5 ms,击败了74.79% 的Java用户
内存消耗:39.5 MB,击败了37.97% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg#pic_center)