1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| func minimumEffortPath(heights [][]int) int { m := len(heights) n := len(heights[0]) directions := [][]int{ {0, -1}, {1, 0}, {0, 1}, {-1, 0}, } var dfs func (heights [][]int, visit []bool, r, c, limit int) bool dfs = func (heights [][]int, visit []bool, r, c, limit int) bool { if visit[r * n + c] { return false } if r == m - 1 && c == n - 1 { return true } visit[r * n + c] = true ans := false for _, direction := range directions { newR := r + direction[0] newC := c + direction[1] if newR >= 0 && newR < m && newC >= 0 && newC < n && abs(heights[newR][newC] - heights[r][c]) <= limit { ans = ans || dfs(heights, visit, newR, newC, limit) } } return ans } left := 0 right := 1000000 for left <= right { mid := ((right - left) >> 1) + left if dfs(heights, make([]bool, m * n), 0, 0, mid) { right = mid - 1 } else { left = mid + 1 } } return left }
func abs(num int) int { if num >= 0 { return num } return -num }
|