Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Mohammed Dh Abbas
I don't think Union Find is the right way to go about this question. modified Dijkstra is the proper way

Mohammed Dh Abbas

Aug 6, 2024

Standard Dijkstra finds the shortest path in directed graph. we could treat the matrix as directed graph.

instead of calculating the new distance to reach a node we could calculate the effort to reach that node "that's the modification "

time complexity = O((NM) log (NM))

from heapq import * class Solution: def get_neighbors(self, x, y, heights): alpha_rows = [-1, 0, 1, 0] alpha_cols = [0, 1, 0, -1] neighbors = [] for i in range(len(alpha_rows)): row = x + alpha_rows[i] col = y + alpha_cols[i] if row >= 0 and row < len(heights) and col >= 0 and col < len(heights[0]): neighbors.append([row, col]) return neighbors def minimumEffortPath(self, heights): cols = len(heights[0]) rows = len(heights) efforts = [[float('inf')] * cols for _ in heights] efforts[0][0] = 0 min_heap = [] heappush(min_heap, (0, 0, 0)) path = {} while min_heap: effort, x, y = heappop(min_heap) if x == rows - 1 and y == cols - 1: # print(path) return effort neighbors = self.get_neighbors(x, y, heights) for nx, ny in neighbors: # either we use the current effort or new effort if it's bigger than the current effort neffort = max(effort, abs(heights[x][y] - heights[nx][ny])) # either smaller than inf or we have found better effort if neffort < efforts[nx][ny]: # for tracking the path. not asked by this question. but that's how you track # path[(x, y)] = (nx, ny) efforts[nx][ny] = neffort heappush(min_heap, (neffort, nx, ny)) return 0

1

0

Comments
Comments

On this page