题目如下:

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?

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:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. 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

最新文章

  1. 【vuejs小项目】一、脚手架搭建工作
  2. snprintf 使用注意
  3. iOS - NSString去掉回车与换行符
  4. [Solved]bcdedit.exe文件权限问题
  5. rest-assured : Restful API 测试利器 - 真正的黑盒单元测试(跟Spring-Boot更配哦,更新至spring-boot1.4.1)
  6. Linq 查询结果 可能遵循 2 º,2¹,2 ²,......增长计算
  7. block 实现原理(内存管理详解)(二)
  8. HTML标签_Form
  9. linux的常用命令及常用快捷键
  10. JS属性读写操作+if判断注意事项
  11. 採訪The Molasses Flood:BioShock Infinite 游戏之后又一大作
  12. 使用C++做算法时,对内存的管理的办法
  13. 【我们一起写框架】MVVM的WPF框架(一)—序篇
  14. redis出现错误:NOAUTH Authentication required.
  15. JIT编译器技术理解
  16. 几种序列化与get、set方法的关系
  17. nginx自动启动脚本
  18. python基础一数据类型之列表
  19. SQL Server 2005 分区表实践——分区切换
  20. PHP:第四章——数组中的排序函数

热门文章

  1. linux(二)用户和用户组管理
  2. PPT技巧
  3. Classic IPC Problems 经典的进程间通信问题
  4. jmeter添加自定义扩展函数之String---base64加密
  5. webstorm启动vue项目配置
  6. LeetCode:旋转数组
  7. VS2017/VS2019 git Authentication failed for "XXXXXXXXXx"
  8. PAT甲级——A1155 HeapPaths【30】
  9. VB - sendKey
  10. [未解决]报错:ssh_exchange_identification: read: Connection reset by peer