【leetcode】207. Course Schedule
2024-09-06 03:11:01
题目如下:
There are a total of n courses you have to take, labeled from
0
ton-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?
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: 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.Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
解题思路:如果某一种输入课程无法被安排,那么一定存在至少这样一门课:通过BFS/DFS的方法从这门课开始,依次遍历需要安排在这门课后面的其他课,最终还会回到这门课,即组成了一个环。我们只有遍历所有的课,看看有没有哪门课会形成环路即可。
代码如下:
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
dic = {}
for cou,pre in prerequisites:
if pre not in dic:
dic[pre] = [cou]
else:
dic[pre].append(cou) for i in range(numCourses):
visit = [0] * numCourses
queue = [i]
start = None
while len(queue) > 0:
inx = queue.pop(0)
if start == None:
start = inx
elif inx == start:
return False
if visit[inx] == 1:
continue
visit[inx] = 1
if inx in dic and len(dic[inx]) > 0:
queue += dic[inx]
return True
最新文章
- 【vuejs小项目】一、脚手架搭建工作
- snprintf 使用注意
- iOS - NSString去掉回车与换行符
- [Solved]bcdedit.exe文件权限问题
- rest-assured : Restful API 测试利器 - 真正的黑盒单元测试(跟Spring-Boot更配哦,更新至spring-boot1.4.1)
- Linq 查询结果 可能遵循 2 º,2¹,2 ²,......增长计算
- block 实现原理(内存管理详解)(二)
- HTML标签_Form
- linux的常用命令及常用快捷键
- JS属性读写操作+if判断注意事项
- 採訪The Molasses Flood:BioShock Infinite 游戏之后又一大作
- 使用C++做算法时,对内存的管理的办法
- 【我们一起写框架】MVVM的WPF框架(一)—序篇
- redis出现错误:NOAUTH Authentication required.
- JIT编译器技术理解
- 几种序列化与get、set方法的关系
- nginx自动启动脚本
- python基础一数据类型之列表
- SQL Server 2005 分区表实践——分区切换
- PHP:第四章——数组中的排序函数
热门文章
- linux(二)用户和用户组管理
- PPT技巧
- Classic IPC Problems 经典的进程间通信问题
- jmeter添加自定义扩展函数之String---base64加密
- webstorm启动vue项目配置
- LeetCode:旋转数组
- VS2017/VS2019 git Authentication failed for ";XXXXXXXXXx";
- PAT甲级——A1155 HeapPaths【30】
- VB - sendKey
- [未解决]报错:ssh_exchange_identification: read: Connection reset by peer