gpt4 book ai didi

python - K 最短路径 Python 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:40:47 24 4
gpt4 key购买 nike

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

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 中使用基本库

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

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')

返回一个空集,而它应该返回路径。

最佳答案

如果您调用 K_shortest_Pathes(graph, "11", "10"),您将永远不会向集合 P 添加元素。阅读我的内联评论。

def K_shortest_Paths(graph,S,T,K=4):
'''Initialize Variables Accordingly'''
B = {}
P = set()
count = {}
for U in graph.keys():
count[U] = 0

# currently the B has only one item, i.e. { S: 0 } => { "11": 0 }
B[S] = 0

'''Algorithm Starts'''
while(len(B)>=1 and count[T]<K):

# results in the only key in B, i.e. PU = S => PU = "11"
PU = min(B,key=lambda x:B[x])

cost = B[PU]

# U = PU[len(PU) - 1], where PU = "11" =>
# U = "11"[len("11")-1] =>
# *** U = "1"
U = PU[len(PU)-1]

del B[PU]
count[U] += 1

# *** U == T => "1" == T => "1" == "10" which is False
# Thus nothing is ever added to set P
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

关于python - K 最短路径 Python 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44100791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com