From 458df737512d64dbdd313498838e85ed1b16b9bd Mon Sep 17 00:00:00 2001 From: jwarren-aifi <112441624+jwarren-aifi@users.noreply.github.com> Date: Mon, 16 Jan 2023 02:26:03 -0800 Subject: [PATCH] find min path --- graphs/minimum_effort_path.py | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/graphs/minimum_effort_path.py b/graphs/minimum_effort_path.py index 74fe13b..a26c0cb 100644 --- a/graphs/minimum_effort_path.py +++ b/graphs/minimum_effort_path.py @@ -1,3 +1,5 @@ +import heapq + def min_effort_path(heights): """ Given a 2D array of heights, write a function to return the path with minimum effort. @@ -15,4 +17,34 @@ def min_effort_path(heights): int minimum effort required to navigate the path from (0, 0) to heights[rows - 1][columns - 1] """ - pass + + if not heights: + return 0 + + effort = [[float("inf") for _ in range(len(heights[0]))] for _ in range(len(heights))] + + nrows = len(heights) + ncols = len(heights[0]) + + pq = [] + + effort[0][0] = 0 + heapq.heappush(pq, (0, 0, 0)) + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + + while pq != []: + effort_till_now, row, col = heapq.heappop(pq) + for i in range(4): + new_row = row + directions[i][0] + new_col = col + directions[i][1] + + if new_row >= 0 and new_row < nrows and new_col >= 0 and new_col < ncols: + + diff = max(effort_till_now, abs( + heights[new_row][new_col] - heights[row][col])) + + if diff < effort[new_row][new_col]: + effort[new_row][new_col] = diff + heapq.heappush(pq, (diff, new_row, new_col)) + + return (effort[nrows-1][ncols - 1])