深度优先在Python中搜索

时间:2012-10-13 14:25:50

标签: python search depth-first-search

我在Python中实现搜索算法时遇到了问题。我需要一个通用的深度优先搜索代码,它可以返回从开始状态到结束状态的路径。

3 个答案:

答案 0 :(得分:4)

从这个essay开始,用Python实现Graphs,然后了解DFS可以使用堆栈弹出并弹出图形的节点。有了这个想法可能会帮助您继续在Python中实现DFS。如果您有具体问题,请在此发布,人们随时准备提供帮助。

答案 1 :(得分:2)

您可以找到详细的实施说明at literateprograms.org

(实际上,它几乎是谷歌的首次亮相,在发布SO问题之前尝试这一点可能会对下次有所帮助)

答案 2 :(得分:1)

使用邻接列表表示来实现图形。实现它的代码如下。 (如果您使用Python读取图表上的文本文件并实现主观性列表,则此代码是特定的)

(Python 3.3)

def ajlist(nameofgraph,start,goal):

x=input("enter the name of the file you want to implement adjecency list: ")##file.txt##
text_file=open(x,"r")
nameofgraph={}##use a dictionary##
for line in text_file:
   (vertex,val)=line.split()
   if vertex not in nameofgraph:
      nameofgraph[vertex]=set9[val])
   else:
      nameofgraph.get[key].add(val)
stack=[(stack,[start])]
while stack:
   (vertex,path)=stack.pop()
   for next in graph[vertex]-set(path):
      if next==goal:
         yield (path+[next])
      else:
         stack.append((next,path+[next]))

如果要运行此功能,请使用此语法list(DFS(nameofgraph,start,goal))

以上是执行DFS并在图中查找路径的最简单方法。如果你在python中实现了一个图形,那么你不需要(输入)函数。然后你要做的就是删除实现的adjecency list部分并使用真实的遍历部分。

相关问题