题目:
你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。请你返回从左上角走到右下角的最小 体力消耗值 。
方法:并查集
class UF :
def __init__(self,size):
self.father={}
#先给每一个键都带上和键一样的值,不然在后面判断左上和右下的时候会出现错误
for x in range(size):
self.father[x]=x
def find (self,x):
root = x
while self.father[root]!=root:
root=self.father[root]
while x != root:
origin_root = self.father[x]
self.father[x] = root
x = origin_root
return root
def union(self,y,x):
x=self.find(x)
y=self.find(y)
if x!=y:
self.father[x]=y
def isconnect(self,y,x):
return self.find(x)==self.find(y)
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
#先假设有一个_y*_x多个的方格,这些方格暂时没有连接。
_y,_x=len(heights),len(heights[0])
side=[]
uf=UF(_y*_x)
for y in range(_y):
for x in range(_x):
#计算每两个方格连接需要多少体力,然后再side列表中保存下[体力,方格1,方格2]
site= y*_x+x#代表方格的位置
if y<_y-1:
side.append([abs(heights[y][x]-heights[y+1][x]),site,site+_x])#[体力,方格1,方格2]
if x<_x-1:
side.append([abs(heights[y][x]-heights[y][x+1]),site,site+1])
side.sort()#因为side列表的第一位是体力值,正好根基体力值排序,从体力值最少的方格两两相连,每连接一次就看看左上与右下是否相连,如果相连就返回当前体力值。(因为最小体力消耗的要求是看体力的值并不是用的所有体力的和)
for j in side:
if uf.isconnect(j[1],j[2]):
continue
uf.union(j[1],j[2])
if uf.isconnect(0,_y*_x-1):
return j[0]
return 0