我试图在python中使用dfs实现一个图形,以找到所有可能的路径来自' A'到' F' 该图表是:
graph = {'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']}
以下是我的代码:
def dfs_path(graph,start,end):
res = []
dfs(graph,start,end,[],res)
return res
def dfs(graph,start,end,path,res):
path+=[start]
if start == end:
res+=[path]
elif not graph.has_key(start):
return
else:
for node in graph[start]:
if node not in path:
dfs(graph,node,end,path,res)
print dfs_path(graph,'A','F')
通过处理打印,我没有得到我想要的,但相反,我得到[['A', 'B', 'D', 'E', 'F', 'C']]
任何人都可以告诉我我的代码有什么问题,如果可能的话,我想知道用相同的格式编写这段代码的正确方法。 感谢
答案 0 :(得分:0)
问题在于你的回溯。搜索以A - >开头。 B - > D,并且在D它达到了死胡同,因为唯一的继承者是B已经被访问过。所以它备份,但你还没有从res中删除D.它只是停留在那里,所以当它继续E - > F,你的结果中仍然有D.
答案 1 :(得分:0)
基本问题是只有一条路径。当您对dfs
进行递归调用时,它会修改path
。当调用返回时,它不会恢复旧值path
。解决这个问题的方法是将path
的副本传递给dfs
。请注意递归调用中的path[:]
。
第二个问题是,当您找到路径时,您将其与res
连接,而您实际上想要将其附加到res
。
在下面的代码中,我已经取消了start
是graph
中的关键字的检查。如果不是graph
中的密钥,就无法将其传递给函数。
graph = {'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']}
def dfs_path(graph,start,end):
result = []
dfs(graph,start,end,[],result)
return result
def dfs(graph,start,end,path,result):
path+=[start]
if start == end:
result.append(path)
else:
for node in graph[start]:
if node not in path:
dfs(graph,node,end,path[:],result)
print(dfs_path(graph,'A','F'))
打印
[['A', 'B', 'E', 'F'], ['A', 'C', 'F']]
看起来对我来说。
我会说你的功能基本上是正确的,但你需要检查python列表的技术性(一般来说可能是可变的数据结构。)
答案 2 :(得分:0)
这是一个带迭代的DFS算法。
def dfs(graph, start):
vertex=start
visited, stack = [vertex], [vertex] #add start index to both visited and stack
while stack: #while stack is not empty
#for each of the children of current vertex we find the first non visited child and add it to visited as well as stack
for i,each in enumerate(graph[vertex]):
if each not in visited:
visited.append(each)
stack+=[each] #push the element to stack if it is visited
vertex=each #change current vertex to last visited vertex
break #since the stack keeps track of the order of elements we can jump to children of current vertex.
else:
#if the length of children of a vertex is reached and all children are visited then pop the last element from stack
if i==len(graph[vertex])-1:
vertex=stack.pop()
break
else:
continue #continue till the end to check if all the children of current vertex are visited
return visited
graph = {'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']}
dfs(graph,'A')
答案 3 :(得分:0)
#Last In First Out
def dfs(G,Source,Goal):
stack=[]
stack_visited_result=[]
stack.append(Source)
stack_visited_result.append(Source)
while len(stack)>0:
print("**********STEP-",len(stack),"**********")
r=0
v=stack[-1]
print("The current stack is ",stack);
if(len(G.get(v))<=0):
print("No key value for the top of the stack",x)
stack.pop()
v=stack[-1]
print("After popping stack",stack)
print ("top of the stack = " , v)
for x in G[v]:
if x not in stack_visited_result:
r=1
print ("value of x(ADJACENT VERTICES) " , x)
stack.append(x)
print("stack ",stack)
if(stack[-1]==Goal):
print("--DESTINATION REACHED----")
print("RESULT FOR DFS ",stack_visited_result)
quit()
stack_visited_result.append(x)
print("stack-visited ",stack_visited_result)
break
if(r is not 1):
print("already visited so,pop the element")
stack.pop()
G={1:[2,3],2:[4,5,6],3:[],4:[],5:[7],6:[],7:[8],8:[]}
dfs(G,1,3)
This code will be used in case of directed graph