From 96aa45ef586c5a31cf4f4c2578f27bf04e4b5c34 Mon Sep 17 00:00:00 2001 From: Grace Date: Mon, 9 Jan 2023 22:11:58 -0800 Subject: [PATCH] All tests pass --- 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..d1c71cb 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 + + max_effort = [[float("inf") for _ in range(len(heights[0]))] for _ in range( + len(heights))] + + n_num_of_rows = len(heights) + n_num_of_cols = len(heights[0]) + + pq = [] + + max_effort[0][0] = 0 + heapq.heappush(pq, (0, 0, 0)) + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + + while pq != []: + max_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 < n_num_of_rows and new_col >= 0 and new_col < n_num_of_cols: + + diff = max(max_effort_till_now, abs( + heights[new_row][new_col] - heights[row][col])) + + if diff < max_effort[new_row][new_col]: + max_effort[new_row][new_col] = diff + heapq.heappush(pq, (diff, new_row, new_col)) + + return (max_effort[n_num_of_rows-1][n_num_of_cols - 1])