-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.py
More file actions
53 lines (49 loc) · 1.17 KB
/
table.py
File metadata and controls
53 lines (49 loc) · 1.17 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Zed
@Version : V1.0.0
------------------------------------
@File : table.py
@Description :
@CreateTime : 2019-12-28 15:47
------------------------------------
@ModifyTime :
"""
def topological_sort2(g):
n = len(g)
# 计算所有结点的入度
in_degree = [0] * n
for i in range(n):
for k in g[i]:
in_degree[k] += 1
# 入度为0的结点
in_degree_0 = []
for i in range(n):
if in_degree[i] == 0:
in_degree_0.insert(0, i)
li = [] # 记录结果
while len(in_degree_0) > 0:
# p出队
p = in_degree_0.pop()
li.append(p)
for k in g[p]:
# 对应结点的入度减1
in_degree[k] -= 1
if in_degree[k] == 0:
in_degree_0.insert(0, k)
return li
if __name__ == '__main__':
# 用邻接表表示图
g2 = [[]] * 13
g2[0] = [1, 5, 6]
g2[2] = [3]
g2[3] = [5]
g2[5] = [4]
g2[6] = [4, 9]
g2[7] = [6]
g2[8] = [7]
g2[9] = [10, 11, 12]
g2[11] = [12]
result2 = topological_sort2(g2)
print(result2)