최 단 경로 알고리즘 - pyth 구현

12776 단어 데이터 구조
Dijkstra 알고리즘

inf = float('inf')

def dijkatra(grah, start):
    #          
    nodeA = [i for i in range(len(grah))]
    nodeA.remove(start)
    #             
    nodeS = [start]
    #       
    res = {}
    lujin = {}
    #            ,       res  
    firstNode = inf
    for i in range(len(grah[start])):
        if grah[start][i] < firstNode:
            firstNode = grah[start][i]
    res[i] = firstNode
    lujin[i] = str(start)+','+str(i)
    nodeS.append(i)
    nodeA.remove(i)
    while nodeA:
        for i in nodeA:
            tmp = inf
            reslujin = ''
            for j in nodeS:
                if j != start:
                    distance = res[j]+grah[j][i]
                    if distance < tmp:
                        tmp = distance
                        reslujin = str(lujin[j])+','+str(i)
            nodeA.remove(i)
            nodeS.append(i)
            res[i] = tmp
            lujin[i] = reslujin
    print(res)
    print(lujin)

if __name__ == '__main__':
    inf = float('inf')
    grah = [[inf, 10, inf, inf,5],[inf, inf, 1, inf, 2],[inf, inf, inf, 4, inf],
            [7, inf, 6, inf, inf],[inf,3, 9, 2, inf]]
    dijkatra(grah, 0)

Floyd 알고리즘


def floyd(grah):
    nodes = len(grah[0])
    for i in range(nodes):
        for j in range(nodes):
            if j == i:
                continue
            for k in range(nodes):
                tmp = grah[j][i] + grah[i][k]
                if grah[j][k] > tmp:
                    grah[j][k] = tmp
    print(grah)


if __name__ == '__main__':
    inf = float('inf')
    grah = [[0, 6, 13],[10, 0, 4],[5, inf, 0]]
    floyd(grah)

좋은 웹페이지 즐겨찾기