From 442eb5e6b4c892069da43433be70056d3c53b057 Mon Sep 17 00:00:00 2001 From: Olena Date: Wed, 18 Jan 2023 20:25:54 -0800 Subject: [PATCH] min_effort_test_pass --- graphs/minimum_effort_path.py | 40 ++++++++++++++++++++++++++++++- requirements.txt | 2 +- tests/test_minimum_effort_path.py | 1 - 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/graphs/minimum_effort_path.py b/graphs/minimum_effort_path.py index 74fe13b..8936a05 100644 --- a/graphs/minimum_effort_path.py +++ b/graphs/minimum_effort_path.py @@ -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. @@ -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)) diff --git a/requirements.txt b/requirements.txt index 77ffa3f..dcb64cf 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 diff --git a/tests/test_minimum_effort_path.py b/tests/test_minimum_effort_path.py index fbad634..cd3b25d 100644 --- a/tests/test_minimum_effort_path.py +++ b/tests/test_minimum_effort_path.py @@ -1,4 +1,3 @@ -import pytest from graphs.minimum_effort_path import *