在图python上找到最短路径

时间:2020-04-22 08:11:31

标签: python python-3.x graph python-2.x shortest-path

我正在编写一个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]]

我没有走最短的路。谁能帮忙吗?

0 个答案:

没有答案
相关问题