diff --git a/graphs/minimum_effort_path.py b/graphs/minimum_effort_path.py index 74fe13b..a720640 100644 --- a/graphs/minimum_effort_path.py +++ b/graphs/minimum_effort_path.py @@ -1,18 +1,26 @@ +import heapq def min_effort_path(heights): - """ Given a 2D array of heights, write a function to return - the path with minimum effort. + if not heights: + return 0 - A route's effort is the maximum absolute difference in heights - between two consecutive cells of the route. + rows = len(heights) + columns = len(heights[0]) + min_effort = 0 + queue = [(0,0,0)] + visited = set() - Parameters - ---------- - heights : list[list[]] (2D array) - 2D array containing the heights of the available paths + while queue: + effort, row, col = heapq.heappop(queue) + visited.add((row, col)) + min_effort = max(min_effort, effort) + if row == rows - 1 and col == columns - 1: + return min_effort + + for x, y in [(0,1), (0, -1), (1,0), (-1, 0)]: + new_row = row + x + new_col = col + y + if rows > new_row >= 0 <= new_col < columns and (new_row, new_col) not in visited: + effort = abs(heights[row][col] - heights[new_row][new_col]) + heapq.heappush(queue, (effort, new_row, new_col)) + return min_effort - Returns - ------- - int - minimum effort required to navigate the path from (0, 0) to heights[rows - 1][columns - 1] - """ - pass