K最短路径Python不起作用 [英] K Shortest Path Python Not Working

查看:136
本文介绍了K最短路径Python不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的K最短路径算法存在某些问题。代码为:

I'm having certain Issues with my K Shortest Path algorithm. The code is given as:

def K_shortest_Paths(graph,S,T,K=4):
    '''Initialize Variables Accordingly'''
    B = {}
    P = set()
    count = {}
    for U in graph.keys():
        count[U] = 0 
    B[S] = 0 
    '''Algorithm Starts'''
    while(len(B)>=1 and count[T]<K):
        PU = min(B,key=lambda x:B[x])
        cost = B[PU]
        U = PU[len(PU)-1]
        del B[PU]
        count[U] += 1 
        if U==T:
            P.add(PU)
        if count[U]<=K:
            V = graph[U].keys()
            for v in V:
                if v not in PU:
                    PV = PU+v
                    B[PV] = cost+1        
    return P

这等效于 https://en.wikipedia.org/wiki/K_shortest_path_routing 提供实施的伪代码。该图给出为:
现在,如果我有开始节点S <10,而终止节点T <10,则它工作良好,但是当S和T> 10时,它返回一个空集,而应该返回路径。请注意,我无法使用Networkx库。我只需要在Python中使用基本库

This is equivalent to https://en.wikipedia.org/wiki/K_shortest_path_routing which provides the Pseudo Code for Implementation. The Graph is given as: Now, It works well if I have Starting Node S<10, and Terminating Node T<10, but with S and T>10, it returns an empty set, Whereas it should return the Path. Please Note that I can't Use Networkx libraries. I only have to Use basic libraries in Python

此外,生成图形的代码是这样的:

Furthermore, the Code to Generate Graph is this:

def create_dictionary(graph):
    D = {}
    for item in graph.items():
        temp = {}
        connected = list(item[1])
        key = item[0]
        for V in connected:
            temp[str(V)] = 1
        D[str(key)] = temp
    return D

def gen_p_graph(nodes,prob):
    if prob>1:
        er='error'
        return er
    graph_matrix=np.zeros([nodes,nodes])
    num_of_connections=int(((nodes * (nodes-1)) * prob  )/2)
    num_list_row=list(range(nodes-1))
    while(np.sum(np.triu(graph_matrix))!=num_of_connections):
            row_num=random.choice(num_list_row)
            num_list_col=(list(range(row_num+1,nodes)))
            col_num=random.choice(num_list_col)
            if graph_matrix[row_num,col_num]==0:
                graph_matrix[row_num,col_num]=1
                graph_matrix[col_num,row_num]=1

    #create dictionary
    df=pd.DataFrame(np.argwhere(graph_matrix==1))
    arr=np.unique(df.iloc[:,0])
    dct={}
    for i in range(graph_matrix.shape[0]):
        dct[str(i)]=set()
    for val in arr:
        dct[str(val)].update(df.loc[df.iloc[:,0]==val].iloc[:,1].values)

    return pd.DataFrame(graph_matrix),dct

我这样运行:

graph= create_dictionary(gen_p_graph(100,0.8)[1])
K_shortest_Paths(graph,'11','10')

返回一个空集合,而

推荐答案

我想您正在尝试实现的目标。试试这个。

What I presume you are trying to achieve. Try this.

def k_shortest_paths(graph, src_node, dest_node, k=4):
  result = []
  pathes = [[src_node]]
  while len(pathes) > 0 and len(result) < k:
    path = pathes.pop()
    last_node = path[-1]
    if last_node == dest_node:
      result.append(path)
    else:
      for child_node in graph[last_node].keys():
        if child_node not in path:
          pathes.append(path + [child_node])
  return result

这篇关于K最短路径Python不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆