[Leetcode] Course Schedule
来源:互联网 发布:8月份经济数据 编辑:程序博客网 时间:2024/05/18 07:41
There are a total of n courses you have to take, labeled from 0
to n - 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?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
public class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { // 0: unvisited, 1: visited, -1: currently searching int[] visit = new int[numCourses]; Map<Integer, List<Integer>> graph = graph(prerequisites); for(int i = 0; i < numCourses; i++) { if(visit[i] == 0 && !GraphNoCycleDfs(graph, visit, i)) { return false; } } return true; } private boolean GraphNoCycleDfs(Map<Integer, List<Integer>> graph, int[] visit, int n) { if(visit[n] == 1) { return true; } if(visit[n] == -1) { return false; } visit[n] = -1; if(graph.containsKey(n)){ List<Integer> adjacentPoint = graph.get(n); for(Integer point : adjacentPoint) { if(!GraphNoCycleDfs(graph, visit, point)) { return false; } } } visit[n] = 1; return true; } private Map<Integer, List<Integer>> graph(int [][] pre) { Map<Integer, List<Integer>> graph = new HashMap<>(); for(int i = 0; i < pre.length; i++) { if(graph.containsKey(pre[i][1])) { graph.get(pre[i][1]).add(pre[i][0]); } else { List<Integer> list = new ArrayList<>(); list.add(pre[i][0]); graph.put(pre[i][1], list); } } return graph; }}
0 0
- Leetcode-Course Schedule && Course Schedule II
- leetcode-Course Schedule
- LeetCode 207 - Course Schedule
- [LeetCode] Course Schedule
- LeetCode Course Schedule
- [leetcode] Course Schedule
- Leetcode Course Schedule
- [leetcode]Course Schedule
- leetcode:Course Schedule
- [leetcode]Course Schedule II
- leetcode - Course Schedule II
- LeetCode Course Schedule II
- [leetcode] Course Schedule II
- [leetcode]Course Schedule
- leetcode:Course Schedule II
- [LeetCode] Course Schedule II
- Leetcode Course Schedule II
- leetcode 207: Course Schedule
- javascript模拟java中的Map
- JavaScript内存泄漏
- Eclipse:source not found
- NHibernate 集合映射基础(第四篇) - 一对一、 一对多、多对多小示例
- 小组件widget
- [Leetcode] Course Schedule
- 单机最大tcp连接数
- linux上运行java程序 jar格式
- Android 适配者模式
- 定义小组件的步骤
- 《Android 开发艺术与探索》笔记——(10)Android 的消息机制
- Activiti工作流框架学习(一)——环境的搭建和数据表的了解
- Android Studio 获取SHA1
- 一点点es6