From 8334af50bb5643c12d759e32557553df6daa7695 Mon Sep 17 00:00:00 2001 From: SaiTeja-002 <95877599+SaiTeja-002@users.noreply.github.com> Date: Mon, 14 Oct 2024 09:53:41 +0530 Subject: [PATCH] Create: 1631-path-with-minimum-effort.py --- python/1631-path-with-minimum-effort.py | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 python/1631-path-with-minimum-effort.py diff --git a/python/1631-path-with-minimum-effort.py b/python/1631-path-with-minimum-effort.py new file mode 100644 index 000000000..64aeb097d --- /dev/null +++ b/python/1631-path-with-minimum-effort.py @@ -0,0 +1,28 @@ +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + m, n = len(heights), len(heights[0]) + + efforts = [[float('inf')] * n for _ in range(m)] + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + + efforts[0][0] = 0 + pq = [(0, 0, 0)] # (effort, row, col) + + while pq: + curEffort, i, j = heapq.heappop(pq) + + # reached the bottom-right corner => return the effort + if i == m - 1 and j == n - 1: + return curEffort + + for dx, dy in directions: + x, y = i + dx, j + dy + + if 0 <= x < m and 0 <= y < n: + newEffort = max(abs(heights[x][y] - heights[i][j]), curEffort) + + if newEffort < efforts[x][y]: + efforts[x][y] = newEffort + heapq.heappush(pq, (newEffort, x, y)) + + return efforts[m - 1][n - 1] \ No newline at end of file