题目:
Given a 2D grid, each cell is either a wall 2, a zombie 1 or people 0 (the number zero, one, two).Zombies can turn the nearest people(up/down/left/right) into zombies every day, but can not through wall. How long will it take to turn all people into zombies? Return -1 if can not turn all people into zombies.
Example
Given a matrix:
0 1 2 0 0
1 0 0 2 1
0 1 0 0 0
return 2
出现bug时应该,写case 来测试每个函数
class Solution:
# @param {int[][]} grid a 2D integer grid
# @return {int} an integer
def zombie(self, grid):
# Write your code here
n, m = len(grid), len(grid[0])
queue = []
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
queue.append((i, j))
p = []
days = 0
while queue:
size = len(queue)
for i in range(size):
i, j = queue.pop(0)
for x, y in self.getNeighbors(grid, i, j):
if grid[x][y] == 0:
p.append((x,y))
queue.append((x, y))
grid[x][y] = 1
days += 1
for i in range(n):
for j in range(m):
if grid[i][j] == 0:
return -1
return days - 1 # 最后一天queue里只有zombie,把queue排空时并没有咬人,所以不算
def getNeighbors(self, grid, i, j):
dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
result = []
for dx, dy in dirs:
if self.inBound(grid, i + dx, j + dy):
result.append((i + dx, j + dy))
return result
def inBound(self, grid, i, j):
n, m = len(grid), len(grid[0])
return i >= 0 and i < n and j >= 0 and j < m # !!!! care j < m 蠢哭
m = [[0,1,2,0,0],
[1,0,0,2,1],
[0,1,0,0,0]]
res = Solution().zombie(m)
print(res) # 2