Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implements solution #80

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions graphs/minimum_effort_path.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import heapq

def min_effort_path(heights):
""" Given a 2D array of heights, write a function to return
the path with minimum effort.

A route's effort is the maximum absolute difference in heights
A route's effort is the maximum absolute difference in heights
between two consecutive cells of the route.

Parameters
Expand All @@ -15,4 +17,32 @@ 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)
columns = len(heights[0])

visited = [[False for _ in range(columns)] for _ in range(rows)]
effort = [[float('inf') for _ in range(columns)] for _ in range(rows)]

effort[0][0] = 0
heap = [(0, 0, 0)]

while heap:
curr_effort, row, col = heapq.heappop(heap)

if visited[row][col]:
continue

visited[row][col] = True

for r, c in [(row-1, col), (row+1, col), (row, col-1), (row, col+1)]:
if 0 <= r < rows and 0 <= c < columns:
new_effort = max(curr_effort, abs(heights[row][col] - heights[r][c]))

if new_effort < effort[r][c]:
effort[r][c] = new_effort
heapq.heappush(heap, (new_effort, r, c))

return effort[rows-1][columns-1]