Я пишу python программу для поиска кратчайшего пути от источника к месту назначения. Мой код:
def gridGraph(row,column):
for x in range(0,row):
for y in range(0,column):
graphNodes.append([x,y])
neighbor1=x+1,y+0
neighbor2=x+0,y+1
weight=randint(1,10)
graph.append([(x,y),(neighbor1),weight])
graph.append([(x,y),(neighbor2),weight])
return graph
def shortestPath(graph,source,destination):
weight=0
path=[]
for data in graph:
if data[0]==source:
path.append(data[1])
weight+=data[2]
if destination == data[0]:
newWeight=checkWeights(weight)
if newWeight<=weight:
print(path)
return path
else:
path.clear()
weight=0
else :
source=data[1]
else:
continue
def checkWeights(weight):
global x
if(weight<=x):
x=weight
return x
else:
return weight
graph=hr.gridGraph(2,2)
hr.shortestPath(graph,(0,0),(0,1))
Мой график выводится в следующем виде:
[[(0, 0), (1, 0), 3], [(0, 0), (0, 1), 3], [(0, 1), (1, 1), 6], [(0, 1), (0, 2), 6], [(1, 0), (2, 0), 4], [(1, 0), (1, 1), 4], [(1, 1), (2, 1), 10], [(1, 1), (1, 2), 10]]
Я не получаю кратчайший путь. Может кто-нибудь, пожалуйста, помогите?