首页 > 其他 > 详细

[LeetCode] 207. Course Schedule

时间:2017-05-22 14:11:59      阅读:379      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/course-schedule

 

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[][] matrix = new int[numCourses][numCourses];
        boolean[] onpath = new boolean[numCourses];
        boolean[] visited = new boolean[numCourses];
        boolean isCycle = false;

        for (int i = 0; i < prerequisites.length; i++) {
            int cur = prerequisites[i][0];
            int pre = prerequisites[i][1];
            matrix[cur][pre] = 1;
        }

        for (int i = 0; i < numCourses; i++) {
            isCycle = isCycle || dfs_cycle(matrix, onpath, visited, i);
        }
        
        return !isCycle;
    }
    
    private boolean dfs_cycle(int[][] matrix, boolean[] onpath, boolean[] visited, int node) {
        if (visited[node]) {
            return false;
        }
        onpath[node] = true;
        visited[node] = true;
        for (int j = 0; j < matrix[node].length; j++) {
            if (matrix[node][j] == 1) {
                if (onpath[j] || dfs_cycle(matrix, onpath, visited, j)) {
                    return true;
                }
            }
        }
        onpath[node] = false;
        return false;
    }
    
}

 

[LeetCode] 207. Course Schedule

原文:http://www.cnblogs.com/chencode/p/course-schedule.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!