经典算法(三)最短路径

2019-08-05  本文已影响0人  一个想当大佬的菜鸡
  • max是一个常数,表示不可达到
  • startIndex表示起点
  • graph是邻接矩阵
  • path和cost是数组,记录上一个节点和当前的最小cost
  • 用visited记录是否访问过
  • 初始化,更新visited[startIndex],更新和startIndex直接相连的cost和path
  • 每次循环,找一个cost最小的节点
    把这个节点加入visited
    更新其他节点:如果没访问过且cost[j] > cost[curIndex] + graph[curIndex][j]
    更新cost[j]和path[j]
#!/bin/python
# -*- coding:utf-8 -*-

def dijkstra(graph, startIndex, path, cost, max):
    m = len(graph)
    visited = [0] * m
    # 初始化
    for i in range(m):
        if i == startIndex:
            visited[i] = 1
        else:
            if graph[startIndex][i] < max:
                cost[i] = graph[startIndex][i]
                path[i] = startIndex
            else:
                cost[i] = max
                path[i] = -1
    # 每次更新一个,需要m-1次
    for i in range(1, m):
        curIndex = -1
        minCost = max
        # 找到最小的
        for j in range(m):
            if visited[j]==0 and cost[j] < minCost:
                minCost = cost[j]
                curIndex = j
        # 均不可达,跳出循环
        if curIndex == -1:
            break
        visited[curIndex] = 1
        # 更新其他
        for j in range(m):
            if visited[j]==0 and cost[j] > cost[curIndex] + graph[curIndex][j]:
                cost[j] = cost[curIndex] + graph[curIndex][j]
                path[j] = curIndex
    return cost, path


if __name__ == '__main__':
    max = 2147483647
    graph = [
        [max, max, 10, max, 30, 100],
        [max, max, 5, max, max, max],
        [max, max, max, 50, max, max],
        [max, max, max, max, max, 10],
        [max, max, max, 20, max, 60],
        [max, max, max, max, max, max],
        ]
    path = [0] * 6
    cost = [0] * 6
    print dijkstra(graph, 0, path
上一篇下一篇

猜你喜欢

热点阅读