求从1到5的最短路径,当前用深度搜索解(强化练习深度搜索练习),效率并不高,因为需要遍历所有情况
备注:
1,深广度遍历图都会得到一棵生成树
2,稀疏图并不适合用邻接表,更适合用链表,此处数据较小可以练习邻接表
import copy data='''4 x 0 1 2 0 4 10 1 2 3 1 4 7 2 0 4 2 3 4 3 4 5 4 2 3''' graph_init_row=data.split("\n") end=int(graph_init_row[0].split(" ")[0]) #初始化邻接表 adj_list=[[0]*5 for i in range(5)] for row in graph_init_row[1:]: row_init=list(map(int,row.split(" "))) adj_list[row_init[0]][row_init[1]]=row_init[2] def dfs(cX,adj,path,value,end,minx): #优化 if sum(value)>minx: return if cX==end: global paths,values paths.append(copy.copy(path)) values.append(copy.copy(value)) thev=sum(value) print("p:",path,"v:",thev) if thev<minx: minx=thev return for x,v in enumerate(adj[cX]): if v!= 0 and x not in path: path.append(x) value.append(v) dfs(x,adj,path,value,end,minx) path.pop() value.pop() paths=[] values=[] p=[0] v=[0] dfs(0,adj_list,p,v,end,float("inf")) vs=list(map(sum,values)) print("最短路径为",paths[vs.index(min(vs))],"最小权重为",min(vs))
来源:https://www.cnblogs.com/shitianfang/p/12402418.html