[Leetcode] Course Schedule

来源:互联网 发布:8月份经济数据 编辑:程序博客网 时间:2024/05/18 07:41

There are a total of n courses you have to take, labeled from 0 to n - 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?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

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.

public class Solution {    public boolean canFinish(int numCourses, int[][] prerequisites) {        // 0: unvisited, 1: visited, -1: currently searching        int[] visit = new int[numCourses];         Map<Integer, List<Integer>> graph = graph(prerequisites);        for(int i = 0; i < numCourses; i++) {            if(visit[i] == 0 && !GraphNoCycleDfs(graph, visit, i)) {                return false;            }        }        return true;    }        private boolean GraphNoCycleDfs(Map<Integer, List<Integer>> graph, int[] visit, int n) {        if(visit[n] == 1) {            return true;        }        if(visit[n] == -1) {            return false;        }                visit[n] = -1;        if(graph.containsKey(n)){            List<Integer> adjacentPoint = graph.get(n);            for(Integer point : adjacentPoint) {                if(!GraphNoCycleDfs(graph, visit, point)) {                    return false;                }            }        }        visit[n] = 1;        return true;    }        private Map<Integer, List<Integer>> graph(int [][] pre) {        Map<Integer, List<Integer>> graph = new HashMap<>();        for(int i = 0; i < pre.length; i++) {            if(graph.containsKey(pre[i][1])) {                graph.get(pre[i][1]).add(pre[i][0]);            }            else {                List<Integer> list = new ArrayList<>();                list.add(pre[i][0]);                graph.put(pre[i][1], list);            }        }        return graph;    }}


0 0
原创粉丝点击