leedcode #210 Course Schedule II

该文介绍了如何解决LeetCode上的第210题,即判断有向图中是否存在环并输出拓扑排序。文中提到了构建有向图、使用defaultdict创建节点、deque进行拓扑排序的关键步骤,并给出了Python实现代码。通过遍历先修课关系,更新节点入度,利用deque存储入度为0的节点进行排序,直到所有边都被处理,若所有边都被移除则表示无环,否则有环。
摘要由CSDN通过智能技术生成

Problem Description

Problem Link

Key points:

  1. Determine whether a directed graph is cyclic.
  2. Output topological ordering.

Tips

Build a directed graph

Define a new class + defaultdict

Define a new class

class GNode(object):
    def __init__(self):
        self.inDegree = 0
        self.outNode = []
  1. Use self.inDegree rather than inDegree.

Defaultdict

import collections from defaultdict
graph = defaultdict(GNode)
  1. Pay attention to the spelling of defaultdict
  2. How does collections.defaultdict work?
    The defaultdict will create a default item (according to your definition) when you try to get an item with a key that is not currently in the dictionary.
    intDict = defaultdict(int) # default item = 0
    listDict = defaultdict(list) # default item = []
    

Deque

from collections import deque
nodeOrder = deque()
nodeOrder.append(node1) # append a new node to tail
nodeOrder.appendleft(node2) # append a new node to head
nodeOrder.pop() # pop from tail
nodeOrder.popleft() # pop from head
## Topological ordering

Topological ordering

  1. Data structure: deque
  2. Intuition:
    2.1 Add all nodes with inDegree == 0 into the deque
    2.2 In each iteration, pop a node with inDegree == 0, the indegree of the outNode relating to this node minus 1. If there exists new node with inDegree == 0, add it into the deque. Repeat untill the deque is empty.
    2.3 Whether is cyclic: if all edges can be removed -> no cycle, vice versa.

Code

class GNode(object):
    def __init__(self):
        self.inDegree = 0
        self.outNode = []

class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: List[int]
        """

        from collections import defaultdict, deque
        graph = defaultdict(GNode)
        courseOrder = []

        for prerequisite in prerequisites:
            nextCourse, prevCourse = prerequisite[0], prerequisite[1]
            graph[prevCourse].outNode.append(nextCourse)
            graph[nextCourse].inDegree += 1
        totalEdges = len(prerequisites)

        nodepCourses = deque()
        for course in range(numCourses):
            if graph[course].inDegree == 0:
                nodepCourses.append(course)
        
        removedEdges = 0
        while nodepCourses:
            course = nodepCourses.popleft()
            courseOrder.append(course)
            for node in graph[course].outNode:
                graph[node].inDegree -= 1
                removedEdges += 1
                if graph[node].inDegree == 0:
                    nodepCourses.append(node)
        
        if totalEdges == removedEdges:
            return courseOrder
        return []
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值