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

jamie horvath c17 #79

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
35 changes: 34 additions & 1 deletion graphs/minimum_effort_path.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from collections import defaultdict
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 +19,33 @@ def min_effort_path(heights):
int
minimum effort required to navigate the path from (0, 0) to heights[rows - 1][columns - 1]
"""
pass
graph = defaultdict(list)
if not heights:
return 0
directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]
rows = len(heights)
cols = len(heights[0])

for x in range(cols):
for y in range(rows):
for direction in directions:
newx, newy = x + direction[0], y + direction[1]
if newx >= 0 and newx < cols and newy >= 0 and newy < rows:
abs_difference = abs(heights[y][x] - heights[newy][newx])
graph[(y,x)].append(((newy, newx), abs_difference))
visited = set()
min_heap = []
start = (0,0)
end = (rows-1, cols-1)
min_heap.append((0, start))
max_abs = 0
while min_heap:
cost_till, curr, = heapq.heappop(min_heap)
visited.add(curr)
max_abs = max(max_abs, cost_till)
if curr == end:
return max_abs
for next, to_reach in graph[curr]:
if next not in visited:
heapq.heappush(min_heap, (to_reach, next))
return max_abs