【发布时间】:2019-04-02 11:53:18
【问题描述】:
我正在学习解决 leetcode 中的拓扑排序问题
总共有 n 门你必须参加的课程,标签从
0到n-1。某些课程可能有先决条件,例如要学习课程 0,您必须先学习课程 1,这表示为一对:
[0,1]鉴于课程总数和先决条件列表pairs,您是否有可能完成所有课程?
示例 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.示例 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.注意:
- 输入先决条件是由边列表表示的图,而不是邻接矩阵。阅读有关how a graph is represented 的更多信息。
- 您可以假设输入先决条件中没有重复的边。
我在讨论区阅读了以下拓扑排序解决方案
class Solution5:
def canFinish(self,numCourses, prerequirements):
"""
:type numCourse: int
:type prerequirements: List[List[int]]
:rtype:bool
"""
if not prerequirements: return True
count = []
in_degrees = defaultdict(int)
graph = defaultdict(list)
for u, v in prerequirements:
graph[v].append(u)
in_degrees[u] += 1 #Confused here
queue = [u for u in graph if in_degrees[u]==0]
while queue:
s = queue.pop()
count.append(s)
for v in graph(s):
in_degrees[v] -= 1
if in_degrees[v] ==0:
queue.append(v)
#check there exist a circle
for u in in_degrees:
if in_degrees[u]:
return False
return True
我对@987654328@感到困惑
for u, v in prerequirements:
graph[v].append(u)
in_degrees[u] += 1 #Confused here
对于有向边 (u,v) , u -----> v ,节点 u 有一个出度,而节点 v 有一个入度。
所以我认为,in_degrees[u] += 1 应该改为in_degrees[v] += 1
因为如果存在 (u,v),那么 v 至少有一个传入事件和一个 indegree
度数:这仅适用于有向图。这表示进入顶点的边数。
但是,原始解决方案有效。
我的理解有什么问题?
【问题讨论】: