Skip to content
Open
Show file tree
Hide file tree
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
40 changes: 39 additions & 1 deletion graphs/minimum_effort_path.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from queue import PriorityQueue

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,40 @@ def min_effort_path(heights):
int
minimum effort required to navigate the path from (0, 0) to heights[rows - 1][columns - 1]
"""
pass
if heights == None:
return 0

rows = len(heights)
columns = len(heights[0])

# Create a 2D array to store the minimum effort required to reach each cell
effort = [[float('inf') for _ in range(columns)] for _ in range(rows)]

# Create a priority queue to store the cells to be processed
q = PriorityQueue()

# Start with the top-left cell
effort[0][0] = 0
q.put((0, 0))

# Define the possible moves
moves = [(1, 0), (-1, 0), (0, 1), (0, -1)]

while not q.empty():
# Get the cell with the minimum effort
row, col = q.get()

# Check the effort required to move to the neighboring cells
for dr, dc in moves:
r, c = row + dr, col + dc
if 0 <= r < rows and 0 <= c < columns:
effort_required = max(abs(heights[r][c] - heights[row][col]), effort[row][col])
if effort_required < effort[r][c]:
effort[r][c] = effort_required
q.put((r, c))
return effort[rows-1][columns-1]

# test the function

heights = [[1,2,2],[3,8,2],[5,3,5]]
print(min_effort_path(heights))
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 0 additions & 1 deletion tests/test_minimum_effort_path.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import pytest
from graphs.minimum_effort_path import *


Expand Down