努橙刷题编

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
    
}

 

posted on 2017-05-22 13:38  努橙  阅读(117)  评论(0编辑  收藏  举报