Bomb Enemy
Problem: Bomb Enemy
Try to scan all possible enemies at starting empty position horizontally and vertically of one free block. Also only count of one previous row is necessary to be stored to save memory.
Code in Python:
class Solution(object):
def maxKilledEnemies(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if len(grid) == 0 or len(grid[0]) == 0: return 0
rows, cols = len(grid), len(grid[0])
res = 0
row = [[0, 0] for _ in xrange(cols)]
prev_row = []
for i in xrange(rows):
for j in xrange(cols):
if grid[i][j] == "W":
continue
if j == 0 or grid[i][j-1] == "W":
count, _j = 0, j
while _j < cols and grid[i][_j] != "W":
if grid[i][_j] == "E": count += 1
_j += 1
row[j][0] = count
else:
row[j][0] = row[j-1][0]
if i == 0 or grid[i-1][j] == "W":
count, _i = 0, i
while _i < rows and grid[_i][j] != "W":
if grid[_i][j] == "E": count += 1
_i += 1
row[j][1] = count
else:
row[j][1] = prev_row[j][1]
if grid[i][j] != "E": res = max(res, sum(row[j]))
prev_row = row
return res