在一个n*n矩阵中,有每一个点都有一个值,小明从左上角走到右下角,求经过所有点的和最小的最短路径
思路:不采用dfs或bfs,将矩阵转换成图,使用dijskstra算法
import numpy as np
import heapq
n = int(input()) # 矩阵大小
temp = np.random.randint(0, 100, size=(n, n)) #随机生成范围在0~100的n*n的矩阵
def dijkstra(adj_list, start, end):
# 初始化距离和前驱节点
dist = {node: float('inf') for node in adj_list}
dist[start] = 0
prev = {node: None for node in adj_list}
# 使用优先队列存储节点和距离信息
pq = [(0, start)]
while pq:
# 取出队列中距离最小的节点
curr_dist, curr_node = heapq.heappop(pq)
if curr_node == end:
# 回溯路径
path = []
node = end
while node is not None:
path.append(node)
node = prev[node]
path.reverse()
return path, curr_dist
# 遍历当前节点的所有邻居节点
for neighbor, weight in adj_list[curr_node]:
new_dist = curr_dist + weight
if new_dist < dist[neighbor]:
# 更新邻居节点的距离和前驱节点
dist[neighbor] = new_dist
prev[neighbor] = curr_node
heapq.heappush(pq, (new_dist, neighbor))
# 如果无法到达终点,返回空列表
return []
# 将矩阵转换为带权值的邻接表
def matrix_to_adj_list(matrix):
n, m = len(matrix), len(matrix[0])
adj_list = {}
for i in range(n):
for j in range(m):
node = (i, j)
neighbors = []
if i > 0:
neighbors.append(((i - 1, j), matrix[i - 1][j]))
if i < n - 1:
neighbors.append(((i + 1, j), matrix[i + 1][j]))
if j > 0:
neighbors.append(((i, j - 1), matrix[i][j - 1]))
if j < m - 1:
neighbors.append(((i, j + 1), matrix[i][j + 1]))
adj_list[node] = neighbors
print(adj_list)
return adj_list
# 使用Dijkstra算法求解左上角到右下角的最短路径
def shortest_path(matrix):
adj_list = matrix_to_adj_list(matrix)
start, end = (0, 0), (len(matrix) - 1, len(matrix[0]) - 1)
return dijkstra(adj_list, start, end)
print(temp)
pathList, shortValue = shortest_path(temp)
print(pathList,"///",shortValue)