Last active
August 13, 2021 02:26
-
-
Save VXU1230/796b6a308e3889ee39b86cd0fe8cff48 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
def dijkstra(grid): | |
seen = set() | |
heap = [] | |
dist = grid[0][0] | |
heapq.heappush(heap, (dist, 0, 0)) | |
row_len = len(grid) | |
col_len = len(grid[0]) | |
min_dist = float('inf') | |
while heap: | |
dist, row, col = heapq.heappop(heap) | |
if row == row_len - 1 and col == col_len - 1: | |
min_dist = min(min_dist, dist) | |
break | |
if (row, col) not in seen: | |
seen.add((row, col)) | |
if row+1 < row_len: | |
heapq.heappush(heap, (dist+grid[row+1][col], row+1, col)) | |
if col+1 < col_len : | |
heapq.heappush(heap, (dist+grid[row][col+1], row, col+1)) | |
return min_dist | |
if __name__ == "__main__": | |
grid = [[1,3,1],[1,5,1],[4,2,1]] | |
print("shortest distance: ", dijkstra(grid)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment