LeetCode 207 Course Schedule

Tech In Pieces發表於2020-11-27

given a 2D array, represents for the class and it’s prerequesite class
like [0,1], it means that we should take class 1 before class 0.

so it is a problem about cycle detection.

public boolean canFinish(int numCourses, int[][] prerequisites)

return if it is possible for us to finish all the courses.

idea:
just test if there exist any cycle in starting from each node, if there is, then we can’t iterate every class, but if there isn’t, then we can.

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        
        for (int[] class_pre: prerequisites) {
            if (map.containsKey(class_pre[1])) {
                map.get(class_pre[1]).add(class_pre[0]);
            } else {
                map.put(class_pre[1], new ArrayList<>());
                map.get(class_pre[1]).add(class_pre[0]);
            }
        }
        boolean[] visited = new boolean[numCourses];
        for (int i = 0; i < numCourses; i++) {
            if (isCycle(i, map, visited)) {
                return false;
            }
        }
        return true; //if there is no cycle in this graph, then we can finish all the courses
    }
    
    private boolean isCycle(int currentNode, HashMap<Integer, List<Integer>> map, boolean[] visited) {
        if (visited[currentNode]) {
            return true;
        }
        if (!map.containsKey(currentNode)) {
            return false;//it actually means that we reached onee path's end
        }
        
        visited[currentNode] = true;
        boolean res = false;
        for (Integer neighbor: map.get(currentNode)) {
            res = isCycle(neighbor, map, visited);
            if (res) {
                break;
            }
        }
        //if any of the res is true, then it is true
        visited[currentNode] = false;
        return res;
    }
}

相關文章