图论DFS获取从起点到终点的路径

时间:2019-01-05 16:02:43

标签: python recursion graph-theory

我只需要一条从源节点到目标节点的路径,即可从此函数返回,但是在发现路径后此函数不会停止。 我只在找到末端节点时才使用return。 找到路径后如何结束此操作。 我的情况只有一条路,没有循环 一个节点最多有四个子节点

def  dfs(gpdic,start,end,visited,path):
   visited[start] = 1
   path.append(start)
   print(f"start node {start}")

   if start == end:
       print(f"this is the path {path}")
       return path
   else:
       print(f"stack {path}")
       for node in gpdic[start]:
           print(f" in node - {node}")
           if visited[node]== -1 and node != -1 and node != 0 :
               print(f" calling for next recursive funtion {node} ")
               dfs(gpdic,node,end,visited,path)
               #return path
    po =  path.pop()
    print(f" poped last {po}")
    visited[start] = -1

if __name__ == '__main__':
    gp = {1: [2, -1, -1, -1], 2: [3, 4, 1, 5], 3: [6, -1, 2, 7],
    4:[-1, -1, -1, 2], 5: [-1, 2, -1, -1], 6: [-1, -1, 3, -1],
    7[-1, 3, -1, -1]}


    visited = [-1] * 12
    path = []
    pathret = dfs(gp,7,4,visited,path)
    print(f"finale path - > {pathret}")

1 个答案:

答案 0 :(得分:0)

解决的问题只需要从函数中获取返回变量并进行比较

def dfs(gpdic,start,end,visited,path):
   visited[start] = 1
   path.append(start)
   print(f"start node {start}")

   if start == end:
       print(f"this is the path {path}")
       return path
   else:
       print(f"stack {path}")
       for node in gpdic[start]:
           print(f" in node - {node}")
           if visited[node]== -1 and node != -1 and node != 0 :
               print(f" calling for next recursive funtion {node} ")
               l = dfs(gpdic,node,end,visited,path)
               if l is not None:
                   return path
    po =  path.pop()
    print(f" poped last {po}")
    visited[start] = -1

if __name__ == '__main__':
    gp = {1: [2, -1, -1, -1], 2: [3, 4, 1, 5], 3: [6, -1, 2, 7],
    4:[-1, -1, -1, 2], 5: [-1, 2, -1, -1], 6: [-1, -1, 3, -1],
    7[-1, 3, -1, -1]}


visited = [-1] * 12
path = []
pathret = dfs(gp,7,4,visited,path)
print(f"finale path - > {pathret}")