gpt4 book ai didi

python - 拓扑排序中的 indegrees 用 Kahn 算法解决 CouseSchedule

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:10 27 4
gpt4 key购买 nike

我正在学习解决 leetcode 中的拓扑排序问题

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.

我在讨论区阅读了以下拓扑排序解决方案

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

我对 in_degrees[u] += 1 感到困惑

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 至少有一个入射事件和一个入度

In Degree: This is applicable only for directed graph. This represents the number of edges incoming to a vertex.

但是,原始解决方案有效。

我的理解有什么问题吗?

最佳答案

看上面那行; 图[v].append(u)。边缘实际上与您的假设和输入格式相反。这是因为对于拓扑排序,我们希望没有依赖项/传入边的事物在结果顺序的前面结束,因此我们根据解释来引导边,“是要求”而不是“需要”。例如。输入对 (0,1) 意味着 0 需要 1,因此在图中我们绘制一条有向边 (1,0),以便 1 在我们的排序中可以排在 0 之前。因此 0 通过考虑这对获得度数。

关于python - 拓扑排序中的 indegrees 用 Kahn 算法解决 CouseSchedule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55474151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com