LeetCode 207. Course Schedule - 拓扑排序(Topological Sort)系列题1

拓扑排序(Topological Sort)在百度百科是这样定义的:对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边∈E(G),则u在线性序列中出现在v之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这个操作称之为拓扑排序。

定义记不住不重要,只要知道拓扑排序(Topological Sort)通常是用来排序具有依赖关系的任务。在LeetCode中207. Course Schedule是拓扑排序最经典的一题。

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return true if you can finish all courses. Otherwise, return false.

Example 1:

Input: numCourses = 2, prerequisites = [[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: numCourses = 2, prerequisites = [[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.

Constraints:

  • 1 <= numCourses <= 105
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.

学习拓扑排序的算法还需要理解两个概念,1)入度:所有指向一个顶点的有向边的数目;2)出度:所有由一个顶点发出的边的数目。

解题思路:

根据课程的关系建立一个有向图,另外还要为每个课程定义一个入度数组,在处理每条边(即有关系的两个课程)时,需要统计入度。例如有两个课程[ai, bi],则bi的入度indegree[bi]加1。

图建立完之后,从入度为0的课程开始处理,可以用BFS,即把入度为0的课程放入队列queue中,每次从队列中取出一个课程,然后把跟该课程相关联的所有课程的入度减1,接着把入度变为0的课程再放入队列中。如此一直循环直到队列为空。

处理完之后,如果还有入度不为0的课程,则表示不可能修完所有课程。

from collections import deque
class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        totalCnt = 0
        finish = 0
        indegree = [0] * numCourses
        graph = [[] for i in range(numCourses)]
        
        for (c1, c2) in prerequisites:
            if c1 == c2:
                return False
            graph[c2].append(c1)
            indegree[c1] += 1
            totalCnt += 1
            
        q = deque()
        for i in range(numCourses):
            if indegree[i] == 0:
                q.append(i)
                
        while len(q) > 0:
            i = q.popleft()
            for c in graph[i]:
                indegree[c] -= 1
                if indegree[c] == 0:
                    q.append(c)
                finish += 1
                    
        return totalCnt == finish

 

你可能感兴趣的:(Leetcode刷题笔记,Sort),leetcode,算法,数据结构,python,拓扑排序)