[LeetCode] 207. Course Schedule
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 207. Course Schedule(拓扑排序)