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.
class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { // check corner cases if (prerequisites.length == 0) { return true; } // set up adjacency list Map<Integer, List<Integer>> adj = new HashMap<>(); for (int i = 0; i < numCourses; i++) { adj.put(i, new ArrayList<Integer>()); } // populate the adjacency list with all nodes' neighbors for (int i = 0; i < prerequisites.length; i++) { adj.get(prerequisites[i][1]).add(prerequisites[i][0]); // directed graph, so only one way } // create a visted array where // 0 = unvisisted // -1 = visisting // 1 = visisted int[] visited = new int[numCourses]; for (int i = 0; i < numCourses; i++) { if(!dfs(adj, visited, i)) { return false; } } return true; } private boolean dfs (Map<Integer, List<Integer>> adj, int[] visited, int i) { // cycle dected, return false if (visited[i] == -1) { return false; } // previous visted, no need to visist again, return true if (visited[i] == 1) { return true; } // currently visiting visited[i] = -1; if (adj.containsKey(i)) { for (int neighbor : adj.get(i)) { // dfs into it's neighbors and retrun false if cycle was found if(!dfs(adj, visited, neighbor)) { return false; } } } // if all the neighbors are visited and no cycle was found, // we mark this node as visited and return true visited[i] = 1; return true; } }