假设有一无向图如上所示,用一个二维数组来保存顶点和边
path = [[1, 2, 7], [1, 3, 9], [1, 6, 14], [2, 4, 15], [2, 3, 10], [3, 4, 11], [3, 6, 2], [4, 5, 6], [5, 6, 9]]
首先创建邻接矩阵
def build_graph(path):
"""创建邻接矩阵 """
max_size = 0
for i in range(len(path)):
max_size = max(max_size, max(path[i][:2]))
max_size += 1
mat = [[0] * max_size for _ in range(max_size)]
for i in range(max_size):
for j in range(max_size):
if i != j:
mat[i][j] = 99999
for i in range(len(path)):
tmp_row = path[i][0]
tmp_col = path[i][1]
weight = path[i][2]
mat[tmp_row][tmp_col] = weight
mat[tmp_col][tmp_row] = weight
return mat
import numpy as np
print(np.array(build_graph(path)))
打印这个邻接矩阵
[[ 0 99999 99999 99999 99999 99999 99999]
[99999 0 7 9 99999 99999 14]
[99999 7 0 10 15 99999 99999]
[99999 9 10 0 11 99999 2]
[99999 99999 15 11 0 6 99999]
[99999 99999 99999 99999 6 0 9]
[99999 14 99999 2 99999 9 0]]
核心代码:
def shortest_path(vertex, graph):
size = len(graph)
distance = graph[vertex]
goal = [0] * size
goal[vertex] = 1
shortest_vertex = vertex
for i in range(1, size):
shortest_dis = 99999
for j in range(1, size):
if goal[j] == 0 and shortest_dis > distance[j]:
shortest_dis = distance[j]
shortest_vertex = j
goal[shortest_vertex] = 1
for j in range(size):
if goal[j] == 0 and distance[shortest_vertex] + graph[shortest_vertex][j] < distance[j]:
distance[j] = distance[shortest_vertex] + graph[shortest_vertex][j]
return distance[1:]
完整代码:
path = [[1, 2, 7], [1, 3, 9], [1, 6, 14], [2, 4, 15], [2, 3, 10], [3, 4, 11], [3, 6, 2], [4, 5, 6], [5, 6, 9]]
def build_graph(path):
"""创建邻接矩阵 """
max_size = 0
for i in range(len(path)):
max_size = max(max_size, max(path[i][:2]))
max_size += 1
mat = [[0] * max_size for _ in range(max_size)]
for i in range(max_size):
for j in range(max_size):
if i != j:
mat[i][j] = 99999
for i in range(len(path)):
tmp_row = path[i][0]
tmp_col = path[i][1]
weight = path[i][2]
mat[tmp_row][tmp_col] = weight
mat[tmp_col][tmp_row] = weight
return mat
def shortest_path(vertex, graph):
size = len(graph)
distance = graph[vertex]
goal = [0] * size
goal[vertex] = 1
shortest_vertex = vertex
for i in range(1, size):
shortest_dis = 99999
for j in range(1, size):
if goal[j] == 0 and shortest_dis > distance[j]:
shortest_dis = distance[j]
shortest_vertex = j
goal[shortest_vertex] = 1
for j in range(size):
if goal[j] == 0 and distance[shortest_vertex] + graph[shortest_vertex][j] < distance[j]:
distance[j] = distance[shortest_vertex] + graph[shortest_vertex][j]
return distance[1:]
weight = build_graph(path)
print(shortest_path(1, weight))
输出:
[0, 7, 9, 20, 20, 11]