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

Julie Warren C17 CSFunB #58

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: 33 additions & 1 deletion graphs/minimum_effort_path.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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])