首页 > 代码库 > [LeetCode] 207. Course Schedule

[LeetCode] 207. Course Schedule

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