问题描述
很显然是一种最短路问题,可以用广度优先来做(可以理解为大水漫灌)
LeetCode代码:
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
length = 0
success = 0
to_check1 = [[0,0]]
to_check2 = []
while to_check1 and not success:
length += 1
while to_check1:
[x,y] = to_check1.pop(0)
if 0 <= x < m and 0 <= y < n and grid[x][y] == 0:
if x == m-1 and y == n-1:
success = 1
break
grid[x][y] = 1
to_check2 += ([[x - 1, y], [x-1,y-1],[x-1,y+1],[x,y-1],[x,y+1],[x + 1, y], [x+1,y-1],[x+1,y+1]])
to_check1 = to_check2
to_check2 = []
if not success:
length = -1
return length
pycharm代码
class Solution:
def shortestPathBinaryMatrix(self, grid):
m = len(grid)
n = len(grid[0])
length = 0
success = 0
to_check1 = [[0,0]]
to_check2 = []
while to_check1 and not success:
length += 1
while to_check1:
[x,y] = to_check1.pop(0)
if 0 <= x < m and 0 <= y < n and grid[x][y] == 0:
if x == m-1 and y == n-1:
success = 1
break
grid[x][y] = 1
to_check2 += ([[x - 1, y], [x-1,y-1],[x-1,y+1],[x,y-1],[x,y+1],[x + 1, y], [x+1,y-1],[x+1,y+1]])
to_check1 = to_check2
to_check2 = []
if not success:
length = -1
return length
grid = [[0,1],[1,0]]
print(Solution().shortestPathBinaryMatrix(grid))
grid = [[0,0,0],[1,1,0],[1,1,0]]
print(Solution().shortestPathBinaryMatrix(grid))
grid = [[1,0,0],[1,1,0],[1,1,0]]
print(Solution().shortestPathBinaryMatrix(grid))