From bc0b1f33f787b6e9e0db506b7bd6e8180cef3b4a Mon Sep 17 00:00:00 2001 From: Huma Hameed Date: Wed, 18 Jan 2023 21:20:02 -0500 Subject: [PATCH] passed all tests --- graphs/minimum_effort_path.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/graphs/minimum_effort_path.py b/graphs/minimum_effort_path.py index 74fe13b..4d137dd 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,27 @@ 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 + + rows, columns = len(heights), len(heights[0]) + + distances = [[float("inf")] * columns for row in range(rows)] + + distances[0][0] = 0 + priority_queue = [(0, 0, 0)] + visited = set() + + while priority_queue: + dist, row, col = heapq.heappop(priority_queue) + if (row, col) == (rows-1, columns -1): + return dist + visited.add((row, col)) + neighbors = [(row-1, col), (row+1, col), (row, col-1), (row, col+1)] + for neighbor in neighbors: + neighbor_row, neighbor_col = neighbor + if (0 <= neighbor_row < rows and 0 <=neighbor_col < columns) and neighbor not in visited: + new_dist = max(dist, abs(heights[row][col] - heights[neighbor_row][neighbor_col])) + if distances[neighbor_row][neighbor_col] > new_dist: + distances[neighbor_row][neighbor_col] = new_dist + heapq.heappush(priority_queue, (max(dist, new_dist), neighbor_row, neighbor_col))