给定一个二维矩阵,每一个格子可能是一堵墙 W、一个敌人E或者空0(数字0)。返回用一个炸弹可杀死的最多敌人数。炸弹会杀死所有在同一行和同一列没有墙阻隔的敌人墙不会被摧毁,只能在空地放置炸弹。
python
class Solution:
def maxKilledEnemies(self, grid):
rows = len(grid)
cows = len(grid[0])
cnt = 0
for i in range(rows):
for j in range(cows):
if grid[i][j] == '0':
# 分析所在行合理范围有几个E,j在变化
s = 0
n = j - 1
while n >= 0:
if grid[i][n] == 'E':
s += 1
elif grid[i][n] == 'W':
break
n -= 1
n = j + 1
while n < cows:
if grid[i][n] == 'E':
s += 1
elif grid[i][n] == 'W':
break
n += 1
# 分析所在列合理范围有几个E, i在变化
n = i - 1
while n >= 0:
if grid[n][j] == 'E':
s += 1
elif grid[n][j] == 'W':
break
n -= 1
n = i + 1
while n < rows:
if grid[n][j] == 'E':
s += 1
elif grid[n][j] == 'W':
break
n += 1
cnt = max(cnt, s)
return cnt
if __name__ == '__main__':
g = [
"0E00",
"E0WE",
"0E00"
]
solution = Solution()
print(solution.maxKilledEnemies(g))