首页 文章

深度优先在Python中搜索

提问于
浏览
-2

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

3 回答

  • 4

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

  • 1

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

    (实际上,它几乎是Google的第一个热门话题,在SO上发布问题之前尝试这一点可能会对下次有帮助)

  • 2

    使用邻接列表表示来实现图形 . 实现它的代码如下 . (如果您使用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部分并使用真正的遍历部分 .

相关问题