题目转化成了, 图中有没有环, 如果有环, 说明就无法上完课, 这里还可以通过记忆化递归, 记忆好某个节点是不是已经确定了不会有环出现了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) { List<List<Integer>> graph = new ArrayList<>(numCourses); for (int i = 0; i < numCourses; i++) { graph.add(new ArrayList<>()); } for (int[] row : prerequisites) { int re = row[0]; int cl = row[1]; graph.get(cl).add(re); } int[] color = new int[numCourses]; for (int i = 0; i < numCourses; i++) { if (color[i] == 0 && hasCircle(graph, i, color)) { return false; } } return true; }
private boolean hasCircle(List<List<Integer>> graph, int course, int[] color) { List<Integer> requires = graph.get(course); if (requires.size() == 0) return false; if (color[course] == 1) return true; if (color[course] == 2) return false; color[course] = 1; for (Integer re : requires) { if (hasCircle(graph, re, color)) { return true; } } color[course] = 2; return false; } }
|