DP-LeetCode361. 轰炸敌人
程序员文章站
2022-03-24 20:42:04
...
1、题目描述
给你一个二维的网格图,网格图中的每一个格子里要么是一堵墙 'W' ,要么是一个敌人 'E' ,要么是一个空位 '0' (数字 0 ),返回你用一个炸弹最多能杀死敌人的数量。
由于墙体足够坚硬,炸弹的威慑力没有办法穿越墙体,所以炸弹只能把所在位置同一行和同一列所有没被墙挡住的敌人给炸死。
注意:你只能把炸弹放在一个空的格子里
2、代码详解
class Solution:
def maxKilledEnemies(self, grid):
# init
if not grid or len(grid) == 0 or len(grid[0]) == 0:
return 0
row, col = len(grid), len(grid[0])
# init
up = [[0] * col for _ in range(row)]
down = [[0] * col for _ in range(row)]
left = [[0] * col for _ in range(row)]
right = [[0] * col for _ in range(row)]
# up:从上到下
for i in range(row):
for j in range(col):
if grid[i][j] != 'W':
if grid[i][j] == 'E':
up[i][j] = 1
if i > 0:
up[i][j] += up[i - 1][j]
# down:从下到上
for i in range(row - 1, -1, -1):
for j in range(col):
if grid[i][j] != 'W':
if grid[i][j] == 'E':
down[i][j] = 1
if i + 1 < row:
down[i][j] += down[i + 1][j]
# right:从右到左
for i in range(row):
for j in range(col - 1, -1, -1):
if grid[i][j] != 'W':
if grid[i][j] == 'E':
right[i][j] = 1
if j + 1 < col:
right[i][j] += right[i][j + 1]
# left:从左到右
for i in range(row):
for j in range(col):
if grid[i][j] != 'W':
if grid[i][j] == 'E':
left[i][j] = 1
if j > 0:
left[i][j] += left[i][j - 1]
# sum
res = 0
for i in range(row):
for j in range(col):
if grid[i][j] == '0': # 找空地
res = max(res, up[i][j] + down[i][j] + left[i][j] + right[i][j])
return res
grid = [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]] # 在位置 (1,1) 放置炸弹可以杀死 3 个敌人。
s = Solution()
print(s.maxKilledEnemies(grid))