Bomb Enemy Problem
Description
LeetCode Problem 361.
Given an m x n matrix grid where each cell is either a wall 'W', an enemy 'E' or empty '0', return the maximum enemies you can kill using one bomb. You can only place the bomb in an empty cell.
The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.
Example 1:

Input: grid = [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
Output: 3
Example 2:

Input: grid = [["W","W","W"],["0","0","0"],["E","E","E"]]
Output: 1
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 500grid[i][j]is either'W','E', or'0'.
Solution
Approach: Four Sweeps with Running Counts
A bomb at an empty cell kills the enemies in its row and column until it hits a wall in each of the four directions. Walking out from every empty cell would cost O(mn(m + n)). Instead, notice that the cells between two walls in a row all see the same enemies to their left and right. Running counts in four sweeps give every cell its total in O(mn).
Keep a grid kills, all zeros at first. Then:
- Sweep each row left to right with a counter
seen: reset it to 0 at a wall, add 1 at an enemy, and addseentokillsfor every cell. At an empty cell,seenis the number of enemies to its left up to the nearest wall. - Do the same right to left, top to bottom and bottom to top.
After the four sweeps, kills[i][j] for an empty cell is the number of enemies it would hit in all four directions. An empty cell never counts itself, so nothing is counted twice. The answer is the largest kills[i][j] over the empty cells, or 0 if the grid has no empty cell (enemy and wall cells also get values, but we skip them).
Complexity: O(mn) time for the four sweeps. O(mn) extra space for kills.
class Solution:
def maxKilledEnemies(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
# kills[i][j]: enemies a bomb at (i, j) would hit, summed over four sweeps.
# Each sweep counts the enemies seen since the last wall in that direction.
kills = [[0] * n for _ in range(m)]
for i in range(m):
for cols in (range(n), range(n - 1, -1, -1)): # left to right, right to left
seen = 0
for j in cols:
if grid[i][j] == "W":
seen = 0
elif grid[i][j] == "E":
seen += 1
kills[i][j] += seen
for j in range(n):
for rows in (range(m), range(m - 1, -1, -1)): # top to bottom, bottom to top
seen = 0
for i in rows:
if grid[i][j] == "W":
seen = 0
elif grid[i][j] == "E":
seen += 1
kills[i][j] += seen
# a bomb may only go on an empty cell (an empty cell never counts itself)
return max((kills[i][j] for i in range(m) for j in range(n) if grid[i][j] == "0"), default=0)