【问题标题】:indegrees in topological sort to solve CouseSchedule with Kahn's algorithm拓扑排序中的 indegrees 以使用 Kahn 算法解决 CouseSchedule
【发布时间】:2019-04-02 11:53:18
【问题描述】:

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

总共有 n 门你必须参加的课程,标签从 0n-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.

注意:

  1. 输入先决条件是由边列表表示的图,而不是邻接矩阵。阅读有关how a graph is represented 的更多信息。
  2. 您可以假设输入先决条件中没有重复的边。

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

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 

我对@9​​87654328@感到困惑

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

度数:这仅适用于有向图。这表示进入顶点的边数。

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

我的理解有什么问题?

【问题讨论】:

    标签: python algorithm


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2014-05-20
      • 2021-07-28
      相关资源
      最近更新 更多