Given an m x n matrix grid where each cell is either a wall 'W', an enemy 'E', or empty '0', return the maximum number of enemies you can kill using one bomb.
The bomb kills all the enemies in the same row and column from the planted point until it hits a wall. You can only place the bomb in an empty cell.
Function Signature
def max_killed_enemies(grid: list[list[str]]) -> int:
Rules
-
The bomb goes in a cell holding
'0'
. It cannot be placed on a wall or on an enemy.
-
From the bomb's cell the blast travels up, down, left and right. In each direction it passes through empty cells and enemies, killing every enemy it reaches, and stops at the first wall or at the edge of the grid.
-
If the grid has no empty cell, return 0.
Constraints
-
m == len(grid)
-
n == len(grid[0])
-
1 <= m, n <= 500
-
grid[i][j]
is either
'W'
,
'E'
, or
'0'
.
Examples
Input: grid = [
["0","E","0","0"],
["E","0","W","E"],
["0","E","0","0"]
]
Output: 3
A bomb at grid[1][1] kills the enemy above at (0, 1), the enemy to the left at (1, 0) and the enemy below at (2, 1). The wall at (1, 2) shields the enemy at (1, 3), and no other empty cell reaches more than 2 enemies.
Input: grid = [
["W","W","W"],
["0","0","0"],
["E","E","E"]
]
Output: 1
Every empty cell is in row 1, which has no enemies. Upward the blast hits a wall at once, and downward it reaches exactly one enemy, so the best any cell can do is 1.
Input: grid = [["0","E","E","W","E"]]
Output: 2
The only empty cell is (0, 0). The blast passes through the enemies at (0, 1) and (0, 2) and stops at the wall at (0, 3), so the enemy at (0, 4) survives.