【发布时间】:2012-03-05 01:43:55
【问题描述】:
目标:尝试将用 python 编写的算法的某些行转换为伪代码。
给定算法的目标:在有向图中找到所有循环。
我的立场:我很了解算法背后的理论,我自己也编写了不同的版本,但是我不能自己编写一个小、高效和正确的算法。
到目前为止我所做的:我无法描述花了多少周的时间在 php 中编写了 Tarjan、各种版本的 DFS、Flloyd 等,但不幸的是,它们只是部分解决方案,必须进一步扩展它们。
另外:我已经在线运行了这个算法并且它有效,我需要它用于我的堆栈并且无法继续进行的学校项目。
这是算法:
def paths_rec(path,edges):
if len(path) > 0 and path[0][0] == path[-1][1]:
print "cycle", path
return #cut processing when find a cycle
if len(edges) == 0:
return
if len(path) == 0:
#path is empty so all edges are candidates for next step
next_edges = edges
else:
#only edges starting where the last one finishes are candidates
next_edges = filter(lambda x: path[-1][1] == x[0], edges)
for edge in next_edges:
edges_recursive = list(edges)
edges_recursive.remove(edge)
#recursive call to keep on permuting possible path combinations
paths_rec(list(path) + [edge], edges_recursive)
def all_paths(edges):
paths_rec(list(),edges)
if __name__ == "__main__":
#edges are represented as (node,node)
# so (1,2) represents 1->2 the edge from node 1 to node 2.
edges = [(1,2),(2,3),(3,4),(4,2),(2,1)]
all_paths(edges)
这是我设法用伪代码编写的,我用#? 标记了我不明白的行。一旦我将它们写成伪代码,我就可以用我非常熟悉的 php 对它们进行编码。
procedure paths_rec (path, edges)
if size(path) > 0 and path[0][0] equals path[-1][1]
print "cycle"
for each element in path
print element
end of for
return
end of if
if size(edges) equals 0
return
end of if
if size(path) equals 0
next_edges equals edges
else
next edges equals filter(lambda x: path[-1][1] == x[0], edges) #?
end of else
for each edge in next_edges
edges_recursive = list(edges) #?
edges_recursive.remove(edge)#?
#recursive call to keep on permuting possible path combinations
paths_rec(list(path) + [edge], edges_recursive)#?
【问题讨论】:
-
一点也不意外,至少你可以把投反对票的原因告诉我,这样我就可以做点什么了,我真的想知道有时是否还有必要再为被爱而烦恼!
标签: python graph-theory pseudocode