題目在此 1091. Shortest Path in Binary Matrix
給定一個地圖找出最短路徑
解題思維
這題很直覺的可以用 Breadth-First Search 來解決問題
一摸到終點就結束了
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: def get_neighbors(y, x): offset = [-1, 0, 1] result = [] for offset_y in offset: new_y = y + offset_y if not 0 <= new_y < length: continue for offset_x in offset: if offset_y == 0 and offset_x == 0: continue new_x = x + offset_x if not (0 <= new_x < length): continue if grid[new_y][new_x] == 1: continue if path_map[new_y][new_x] != -1: continue result.append((new_y, new_x)) return result length = len(grid[0]) if length <= 1: return length if grid[0][0] == 1 or grid[length - 1][length - 1] == 1: return -1 path_map = [[-1 for _ in range(length)] for _ in range(length)] path_map[0][0] = 1 changed_0 = [(0, 0)] changed_1 = [] while changed_0: for y, x in changed_0: neighbors = get_neighbors(y, x) new_result = path_map[y][x] + 1 if (length - 1, length - 1) in neighbors: return new_result for n_y, n_x in neighbors: path_map[n_y][n_x] = new_result changed_1.extend(neighbors) changed_0 = changed_1 changed_1 = [] return -1
|
也許你也會想看看