Python Kahn算法求解CouseSchedule的拓扑排序中的索引

Python Kahn算法求解CouseSchedule的拓扑排序中的索引,python,algorithm,Python,Algorithm,我正在学习解决leetcode中的拓扑排序问题 您必须参加的课程总共有n门,标记为从0到n-1 某些课程可能有先决条件,例如,要选修课程0,您必须首先选修课程1,课程1表示为一对:[0,1] 考虑到课程总数和必修课对列表,您是否可以完成所有课程 例1: 例2: 注: 输入先决条件是由边列表表示的图形,而不是邻接矩阵。阅读更多关于。 您可以假定输入先决条件中没有重复的边。 我在讨论区阅读了以下拓扑排序解决方案 class Solution5: def canFinish(self,numC

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

您必须参加的课程总共有n门,标记为从0到n-1

某些课程可能有先决条件,例如,要选修课程0,您必须首先选修课程1,课程1表示为一对:[0,1]

考虑到课程总数和必修课对列表,您是否可以完成所有课程

例1:

例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 
我对in_度[u]+=1感到困惑

对于有向边u,v,u--->v,节点u有一个outdegree,而节点v有一个indegree

所以我认为,in_度[u]+=1应该改为in_度[v]+=1 因为如果存在u,v,那么v至少有一个传入事件和一个indegree

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

然而,最初的解决方案是有效的

我的理解有什么问题吗?

看看上面这行;图[v].附录U。这些边实际上与您的假设和输入格式的方向相反。这是因为对于拓扑排序,我们希望没有依赖项/传入边的东西最终位于结果顺序的前面,因此我们根据解释来引导边,这是一个要求,而不是要求。输入对0,1意味着0需要1,所以在图中我们画了一条有向边1,0,这样在我们的排序中1可以先于0。因此,0从考虑这一对中获得了独立性

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.
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 
for u, v in prerequirements:
    graph[v].append(u)
    in_degrees[u] += 1 #Confused here