本题是一个很经典的图论问题,可以简化为判断有向图是否有环。
class Solution { private Map<Integer, List<Integer>> graph= new HashMap<>(); private int[] visited; public boolean canFinish(int numCourses, int[][] prerequisites) { for(int[] edge: prerequisites){ graph.putIfAbsent(edge[1], new ArrayList<>()); graph.get(edge[1]).add(edge[0]); } // states: 0 = unknown, 1 == visiting, 2 = visited visited = new int[numCourses]; for(int node = 0; node < numCourses; node++){ if(visited[node] == 0 && isCycle(node)) return false; } return true; } public boolean isCycle(int cur){ if(visited[cur] == 1) return true; if(visited[cur] == 2) return false; if(!graph.containsKey(cur)) return false; //bug 先返回 再赋值 visited[cur] = 1; for(int next: graph.get(cur)){ if(isCycle(next)) return true; } visited[cur] = 2; return false; } }