diff --git a/graphs/minimum_effort_path.py b/graphs/minimum_effort_path.py index 74fe13b..ac95dc7 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,31 @@ 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 = len(heights) + cols = len(heights[0]) + visited = set() + + min_eff = 0 + start = [(0, 0, 0)] + dirs = [(-1, 0), (0, 1), (0, -1), (1, 0)] + + while start: + eff, row, col = heapq.heappop(start) + visited.add((row, col)) + min_eff = max(min_eff, eff) + + if row == rows - 1 and col == cols - 1: + return min_eff + + for x_coor, y_coor in dirs: + next_row = row + x_coor + next_col = col + y_coor + + if rows > next_row >= 0 <= next_col < cols: + if (next_row, next_col) not in visited: + heapq.heappush(start, (abs(heights[row][col] - heights[next_row][next_col]), next_row, next_col)) + + return min_eff diff --git a/requirements.txt b/requirements.txt index 77ffa3f..dcb64cf 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,5 +4,5 @@ packaging==20.8 pluggy==0.13.1 py==1.10.0 pyparsing==2.4.7 -pytest==6.2.1 +pytest==6.2.5 toml==0.10.2