[LeetCode] 207 Course Schedule_Medium tag: BFS, DFS
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:
- 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.
我的理解是这个题就是问, 如果有两门课互为prerequisite课, 那么就False, 否则True, 注意的是这里的互为有可能是中间隔了几门课, 而不是直接的prerequisite, 例如: [(0,1),(2,0),(1,2)], 这里 1 是0 的前置课, 0 是2 的前置课, 所以1是2 的间接前置课, 但是最后一个input说2 是1 的前置课, 所以就矛盾, 不可能完成, return False. 所以思路为, 建一个dictionary, 分别将input 的每个pair(c1, c2)放入dictionary里面, 前置课(c2)为key, 后置课(c1)为value, 不过放入之前要用bfs 判断c1 是否为c2 的前置课, 如果是, 那么矛盾, return False. 否则一直判断到最后的pair, 返回Ture.
12/05/2019 Update: 这个题目实际上是有向图里面找是否有环的问题。用dfs去遍历每个graph的点,可以参考Directed Graph Loop detection and if not have, path to print all path. T: O(n) S: O(n)
1. Constraints:
1) 实际这里的n对我这个做法没有什么用处, 因为课程id 是unique的.
2. Ideas
BFS: T: O(n) number of nodes, S: O(n^2)
1) init dictionary, d
2) for pair(c1,c2) in prerequisites, use bfs to see if c1 is a prerequisity of c2, if so , return False, else, d[c2].add(c1), and until all pairs been checked. return True
3) bfs: use queue and visited to check whether there is a path from source to target.
3. Code
class Solution:
def courseSchedule(self, numCourse, prerequisites):
def bfs(d, source, target):
if source not in d: return False
queue, visited = collections.deque([source]), set([source])
while queue:
node = queue.popleft()
if node == target: return True
for each in d[node]:
if each not in visited:
queue.append(each)
visited.add(each)
return False d = collections.defaultdict(set)
for c1, c2 in prerequisites:
if bfs(d,c1, c2): return False
d[c2].add(c1)
return True
4. Test cases:
1) [(0,1),(2,0),(1,2)], => False
[LeetCode] 207 Course Schedule_Medium tag: BFS, DFS的更多相关文章
- [LeetCode] 490. The Maze_Medium tag: BFS/DFS
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] 133. Clone Graph_ Medium tag: BFS, DFS
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- [LeetCode] 529. Minesweeper_ Medium_ tag: BFS
Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representin ...
- [LeetCode] 690. Employee Importance_Easy tag: BFS
You are given a data structure of employee information, which includes the employee's unique id, his ...
- [LeetCode] 733. Flood Fill_Easy tag: BFS
An image is represented by a 2-D array of integers, each integer representing the pixel value of the ...
- [LeetCode] 130. Surrounded Regions_Medium tag: DFS/BFS
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A reg ...
- [LeetCode] 849. Maximize Distance to Closest Person_Easy tag: BFS
In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is emp ...
- [LeetCode] 513. Find Bottom Left Tree Value_ Medium tag: BFS
Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...
- [LeetCode] 821. Shortest Distance to a Character_Easy tag: BFS
Given a string S and a character C, return an array of integers representing the shortest distance f ...
随机推荐
- 【linux系列】压缩和解压缩tar
tar -c: 建立压缩档案-x:解压-t:查看内容-r:向压缩归档文件末尾追加文件-u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用其中一个.下面的 ...
- eclipse中改变默认的workspace的方法
1.File-->Switch Workspace-->Other 2.Window-->Preferences-->General-->Startup and Shui ...
- RunAsDate v1.36 突破软件试用30天的工具
http://www.nirsoft.net/utils/run_as_date.html RunAsDate v1.36 - Run a program with the specified dat ...
- angularjs结合html5的拖拽行为
闲聊: 小颖公司的项目之前要实现一个将左侧树中当前拖拽的内容,动态添加到右侧树种,虽然这个模块当时没有分给小颖,是同事完成的(小颖也不会嘻嘻),后来看了下他写代码,小颖自己写了个小demo.就当做个笔 ...
- sencha touch 在线实战培训 第一期 第八节 (完结)
2014.1.15晚上8点开的课 这是本期课程的最后一课,下期课程预计在春节后继续. 如果你有什么意见和建议可以将他们发送到邮箱:534502520@qq.com 本期培训一共八节,前三堂免费,后面的 ...
- nginx 日志文件
默认日志格式 log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status ...
- 【CF875E】Delivery Club 二分+线段树
[CF875E]Delivery Club 题意:有n个快递需要依次接收,这n个快递分部在x轴上,第i个快递的位置是xi.有两个快递员,一开始分别在s0,s1,你可以任意安排哪个人收哪个快递,前提是一 ...
- 【BZOJ2310】ParkII 插头DP
[BZOJ2310]ParkII Description Hnoi2007-Day1有一道题目 Park:给你一个 m * n 的矩阵,每个矩阵内有个权值V(i,j) (可能为负数),要求找一条回路, ...
- python获取windows所有com口
import serial import serial.tools.list_ports port_list = list(serial.tools.list_ports.comports()) po ...
- python的十进制与任意进制的转换
将任意进制转换成十进制 ", 8)) # 表示把8进制的54转换成十进制数并输出结果. # 8可以是2.8,10,16等进制数 将十进制转换成任意进制 def f(n,x): #n为待转换的 ...