题目描述:你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。
请你返回从左上角走到右下角的最小 体力消耗值 。
解题思路:将问题转化为图论问题,图中每个方格为一个节点,每个节点的上下左右节点之间都连接着无向边,边的权重为节点高度差的绝对值,需要求从左上角到右下角的最短路径,路径长度定义为经过路径的所有边权的最大值,将所有边按照权重排序,利用并查集依次加入每天边,只要当左上角节点和右下角节点属于同一个集合,返回最后加入的边的权重即可。
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
rows, cols = len(heights), len(heights[0])
father = list(range(rows * cols))
edges = []
for i in range(rows):
for j in range(cols):
iden = i * cols + j
if i > 0:
edges.append([iden - cols, iden, abs(heights[i][j] - heights[i-1][j])])
if j > 0:
edges.append([iden-1, iden, abs(heights[i][j] - heights[i][j-1])])
edges.sort(key=lambda x:x[2])
def find(x):
root = x
while(root != father[root]):
root = father[root]
while(x != root):
origin_r = father[x]
father[x] = root
x = origin_r
return root
def union(x, y):
rootx, rooty = find(x), find(y)
if rootx == rooty:
return True
father[rootx] = rooty
return False
for u,v,w in edges:
union(u, v)
if find(0) == find(rows*cols-1):
return w
return 0