【发布时间】:2014-06-05 03:57:40
【问题描述】:
这是我为 Kosaraju 算法编写的第一部分代码。
###### reading the data #####
with open('data.txt') as req_file:
ori_data = []
for line in req_file:
line = line.split()
if line:
line = [int(i) for i in line]
ori_data.append(line)
###### forming the Grev ####
revscc_dic = {}
for temp in ori_data:
if temp[1] not in revscc_dic:
revscc_dic[temp[1]] = [temp[0]]
else:
revscc_dic[temp[1]].append(temp[0])
print revscc_dic
######## finding the G#####
scc_dic = {}
for temp in ori_data:
if temp[0] not in scc_dic:
scc_dic[temp[0]] = [temp[1]]
else:
scc_dic[temp[0]].append(temp[1])
print scc_dic
##### iterative dfs ####
path = []
for i in range(max(max(ori_data)),0,-1):
start = i
q=[start]
while q:
v=q.pop(0)
if v not in path:
path.append(v)
q=revscc_dic[v]+q
print path
代码读取数据并正确形成 Grev 和 G。我已经为迭代 dfs 编写了代码。我怎样才能找到完成时间?我了解使用纸和笔查找完成时间,但我不理解完成时间作为代码的部分??我该如何实现它。只有在此之后,我才能继续我的下一部分代码。请帮忙。提前致谢。
data.txt 文件包含:
1 4
2 8
3 6
4 7
5 2
6 9
7 1
8 5
8 6
9 7
9 3
请将其另存为 data.txt。
【问题讨论】:
-
完成时间是什么意思?
-
Kosaraju 算法的思路是这样的: 1. 对反转图做DFS,计算所有顶点的完成时间; 2.将顶点索引替换为其完成时间得到一个新图,对新图进行DFS计算每个顶点的领导顶点(如果存在,则在强连接组件(SCC)中); 3. 对leader vertices的索引进行统计。如果多个顶点具有相同的领导者顶点,则它们在同一个 SCC 中。
-
啊,你的意思是拓扑排序。
-
保持计数器初始化为 N。在逆向图上执行 DFS 时,一旦访问顶点,将该顶点的拓扑顺序(完成时间)标记为计数器值并递减计数器.
-
@Abinaya 你能告诉我如何找到完成时间吗?
标签: python algorithm kosaraju-sharir