Topological Sorting

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

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

有向无环图(DAG)才有拓扑排序,非DAG图没有拓扑排序一说。例如,下面这个图:

它是一个 DAG 图,那么如何写出它的拓扑排序呢?这里说一种比较常用的方法:

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

于是,得到拓扑排序后的结果是[1, 2, 4, 3, 5]。 通常,一个有向无环图可以有一个或多个拓扑排序序列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def topoSort(G):
in_degree = {node:0 for node in G}
for u in G:
for v in G[u]:
in_degree[v] += 1

queue = [u for u in in_degree if in_degree[u] == 0]
res = []
while queue:
s = queue.pop()
res.append(s)
for u in G[s]:
in_degree[u] -= 1
if in_degree[u] == 0:
queue.append(u)
return res

G={
1: [2,4],
2: [3,4],
3: [5],
4: [3,5],
5: [],
}

res=topoSort(G)
print(res)

Leetcode 207 Course Schedule

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 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.
Example 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.
Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
G = {node:[] for node in range(numCourses)}
for edge in prerequisites:
G[edge[1]].append(edge[0])


def top_sort(G):
in_degree = {node: 0 for node in G}

for u in G:
for v in G[u]:
in_degree[v] += 1

queue = [node for node in in_degree if in_degree[node] == 0]
res = []
while queue:
cur_node = queue.pop()
res.append(cur_node)

for v in G[cur_node]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)

return True if len(res) == len(G) else False

return top_sort(G)

reference https://blog.csdn.net/lisonglisonglisong/article/details/45543451

Donate article here