【LeetCode】207 and 210(图论,有向图的环检测和拓扑排序)

图数据结构

除 「遍历 + 访问」 这两种数据结构相关的基本算法外。图这种数据结构还有⼀些⽐较特殊的算法,⽐如⼆分图判断,有环图⽆环图的判断,拓扑排序,以及最经典的最⼩⽣成树,单源最短路径问题,更难的就是类似⽹络流这样的问题。
本⽂就结合具体的算法题,来说两个图论算法:有向图的环检测、拓扑排序算法。

207. 课程表

【LeetCode】207 and 210(图论,有向图的环检测和拓扑排序)_第1张图片
【LeetCode】207 and 210(图论,有向图的环检测和拓扑排序)_第2张图片
解法:深度优先遍历(DFS)
可以将图结构类比为多叉树的遍历,添加⼀个布尔数组 onPath 记录当前
遍历 经过的路径:在进⼊节点 s 的时候将 onPath[s] 标记为 true,离开时标记回 false,如果发现 onPath[s] 已经被标记,说明出现了环。
这样,就可以在遍历图的过程中顺便判断是否存在环了,完整代码如下:

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        graph = collections.defaultdict(list)
        for i in range(numCourses):
            graph[i] = []
        for courses in prerequisites:
            graph[courses[1]].append(courses[0])
        hasCycle = False
        onPath = collections.defaultdict(bool)
        visited = set([])
        def traverse(node):
            nonlocal graph
            nonlocal onPath
            nonlocal hasCycle

            if onPath[node]:
                hasCycle = True
                return
            if node in visited:
                return
            
            visited.add(node)
            onPath[node] = True
            for subNode in graph[node]:
                traverse(subNode)
            onPath[node] = False
        for node in graph:
            traverse(node)
        return not hasCycle

210. 课程表2

【LeetCode】207 and 210(图论,有向图的环检测和拓扑排序)_第3张图片
【LeetCode】207 and 210(图论,有向图的环检测和拓扑排序)_第4张图片
解法:拓扑排序(正向思维)
正向思维:每个状态下选择1门入度为0的课程去上(即不需要前置课程),若没有可供选择的课程,则退出选择。若选择课程数量等于numCourses则返回选择结果,否则表明内部存在环结构,返回空列表。
具体步骤如下:

  1. 从 DAG 图(有向无环图)中选择一个 没有前驱(即入度为0)的顶点并输出。
  2. 从图中删除该顶点和所有以它为起点的有向边。
  3. 重复 1 和 2 直到当前的 DAG 图为空或当前图中不存在无前驱的顶点为止。后一种情况说明有向图中必然存在环。

示例如下:
【LeetCode】207 and 210(图论,有向图的环检测和拓扑排序)_第5张图片

上述解法中,在构造图的过程中,除了要创建邻接表外,还需要维护一个入度字典用于存储图中各个节点的入度。

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        graph, indegrees = self.buildGraph(numCourses, prerequisites)
        # 入度为0的节点队列
        nodeSet = []
        # 初始化节点队列
        for node in indegrees:
            if indegrees[node] == 0:
                nodeSet.append(node)
        result = []
        # 当没有可供选择的节点,退出循环
        while nodeSet:
        	# 被选择节点,从图中删除
            node = nodeSet.pop()
            result.append(node)
            # 更新删除node节点后图中相关节点的入度信息,若为0则加入待选择队列中
            for nextNode in graph[node]:
                indegrees[nextNode] -= 1
                if indegrees[nextNode] == 0:
                    nodeSet = [nextNode] + nodeSet
        if len(result) == numCourses:
            return result
        else:
            return []
    def buildGraph(self, numCourses, prerequisites):
    	# 邻接表和入度字典
        graph = collections.defaultdict(list)
        indegrees = {}
        for i in range(numCourses):
            graph[i] = []
            indegrees[i] = 0
        
        for courses in prerequisites:
            graph[courses[1]].append(courses[0])
            indegrees[courses[0]] += 1

        return graph, indegrees

解法2:拓扑排序(逆向思维)
我们观察到图结构的后序遍历,是在遍历左右子树后再处理根节点,此情况下代入该题,表明其前置课程都已满足,可以选择根节点课程。因此对DAG的后序遍历结果为拓扑排序的逆序结果。

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
    	# 邻接表
        graph = self.buildGraph(numCourses, prerequisites)
        # 存储后续遍历结果
        result = []
        # 判断当前节点是否访问过
        visited = set()
        # 判断是否存在环结构
        onPath = collections.defaultdict(bool)
        hasCycle = False
        def traverse(node):
            nonlocal visited
            nonlocal result 
            nonlocal graph
            nonlocal hasCycle
            if onPath[node]:
                hasCycle = True
                return
            if node in visited:
                return
            visited.add(node)
            onPath[node] = True
            for subNode in graph[node]:
                traverse(subNode)
            result.append(node)
            onPath[node] = False
        for node in graph:
            traverse(node)
        # 若无环,逆后序遍历结果即为拓扑排序结果
        return [] if hasCycle else result[::-1]
    def buildGraph(self, numCourses, prerequisites):
        graph = collections.defaultdict(list)
        for i in range(numCourses):
            graph[i] = []
        
        for courses in prerequisites:
            graph[courses[1]].append(courses[0])

        return graph

总结

一、什么是拓扑排序

在图论中,拓扑排序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列。且该序列必须满足下面两个条件:

  1. 每个顶点出现且只出现一次。
  2. 若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面。

有向无环图(DAG)才有拓扑排序,非DAG图没有拓扑排序一说。

二、图的遍历框架

图和多叉树最⼤的区别是,图是可能包含环的,你从图的某⼀个节点开始遍历,有可能⾛了⼀圈⼜回到这个节点。
所以,如果图包含环,遍历框架就要⼀个 visited 数组进⾏辅助:
【LeetCode】207 and 210(图论,有向图的环检测和拓扑排序)_第6张图片

你可能感兴趣的:(Leetcode小刷一下,图论,leetcode,算法,深度优先遍历,拓扑排序)