LeetCode 207. Course Schedule

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

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.

Solution:

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList[] graph = new ArrayList[numCourses];
        for(int i = 0; i < numCourses; ++i)
            graph[i] = new ArrayList();
        boolean[] dp = new boolean[numCourses];

        boolean visited[] = new boolean[numCourses];
        for(int i = 0; i < prerequisites.length; ++i)
            graph[prerequisites[i][1]].add(prerequisites[i][0]);

        for(int i = 0; i < numCourses; ++i)
            if(!dfs(graph, i, visited, dp))
                return false;

        return true;
    }

    //dfs to check whether the graph has cycle
    public boolean dfs(ArrayList[] graph, int course, boolean[] visited, boolean[] dp) {

        if(visited[course]) {
            dp[course] = false;
            return false;
        }

        else
            visited[course] = true;

        for(int i = 0; i < graph[course].size(); ++i)
            if(!dfs(graph, (int) graph[course].get(i), visited, dp)) {
                dp[course] = false;
                return false;
            }

        visited[course] = false;

        dp[course] = true;
        return true;
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值