return dfs(i + 1, j, heights[i][j], target) or dfs(i - 1, j, heights[i][j], target) or dfs(i, j + 1, heights[i][j], target) or dfs(i, j - 1, heights[i][j], target)
而不是写出下面的代码(下面的代码会超时):
top =dfs(i +1, j, heights[i][j], target)bottom =dfs(i -1, j, heights[i][j], target)right =dfs(i, j +1, heights[i][j], target)left =dfs(i, j -1, heights[i][j], target)return top or bottom or right or left
代码
代码支持:Python3
classSolution:defminimumEffortPath(self,heights: List[List[int]]) ->int: lo, hi =0,10**6-1 m, n =len(heights),len(heights[0])defdfs(i,j,pre,target):if (i, j) in visited:returnFalseif i <0or i >= m or j <0or j >= n orabs(heights[i][j] - pre)> target:returnFalseif i == m -1and j == n -1:returnTrue visited.add((i, j)) return dfs(i + 1, j, heights[i][j], target) or dfs(i - 1, j, heights[i][j], target) or dfs(i, j + 1, heights[i][j], target) or dfs(i, j - 1, heights[i][j], target)
# 查找最右侧满足条件的值while lo <= hi: visited =set() mid = (lo + hi) >>1ifdfs(0, 0, heights[0][0], mid): hi = mid -1else: lo = mid +1return lo
复杂度分析
m 为 矩阵的高度, n 为矩阵的长度。
时间复杂度:$O(4 \times m \times n \times log_2 10^6)$,其中 $log_2 10^6$ 为二分的次数, $4 \times m \times n$ 为每次 dfs 的时间。