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

CS Fun A - Ivana #78

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
32 changes: 31 additions & 1 deletion graphs/minimum_effort_path.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
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 +18,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
# Get the number of rows and columns
rows, columns = len(heights), len(heights[0])

# Initialize the distances array with infinity
distances = [[float('inf')] * columns for _ in range(rows)]
pq = []

distances[0][0] = 0
# Push the starting point into the heap
heapq.heappush(pq, (0, 0, 0))

while pq:
distance, row, column = heapq.heappop(pq)
if row == rows - 1 and column == columns - 1:
return distance

# Check the four possible neighbors
for r, c in ((row + 1, column), (row - 1, column), (row, column + 1), (row, column - 1)):
# Check if the neighbor is within array
if 0 <= r < rows and 0 <= c < columns:
# Calculate the new distance
new_distance = max(distance, abs(heights[r][c] - heights[row][column]))
if new_distance < distances[r][c]:
distances[r][c] = new_distance
# Push the new distance into the heap
heapq.heappush(pq, (new_distance, r, c))