目标:尝试将用python编写的算法的某些行转换为伪代码。
给定算法的目标:查找带有周期的有向图中的所有周期。
我的立场:我很好理解算法背后的理论,我自己也编写了不同的版本,但是我不能自己编写一个小,高效和正确的算法。
到目前为止我做了什么:我无法描述花了多少星期,编写了Tarjan,各种版本的DFS,Flloyd等在php中,但不幸的是它们只是部分解决方案而且必须扩展它们。
另外:我已经在线运行了这个算法并且它有效,我需要它用于我堆叠的学校项目,不能继续进行。
这是算法:
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)#?
答案 0 :(得分:1)
第next_edges = filter(lambda x: path[-1][1] == x[0], edges)
行创建一个新列表,其中包含edges
中的第一个点与当前路径的最后一个元素的第二个点相同的边,并等同于
next_edges = []
for x in edges:
if path[len(path) - 1][1] == x[0]
next_edges.append[x]
这些行创建了边缘列表edges
的新副本,因此当从此副本中删除edge
时,它不会更改列表edges
edges_recursive = list(edges)
edges_recursive.remove(edge)
paths_rec(list(path) + [edge], edges_recursive)
只是recursive call,其中添加了edge
的路径以及从中删除了edge
的新边缘列表。