Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum 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 the wall since the wall is too strong to be destroyed.
Note: You can only put the bomb at an empty cell.
Input: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]Output: 3Explanation: For the given grid,0 E 00E 0 W E
0 E 00Placing a bomb at(1,1) kills 3 enemies.
The key idea is to efficiently count the number of enemies that can be killed from each empty cell by precomputing the number of enemies in all four directions (left, right, up, down) until a wall is encountered. This avoids redundant counting and speeds up the solution.
classSolution {
funmaxKilledEnemies(grid: Array<CharArray>): Int {
if (grid.isEmpty() || grid[0].isEmpty()) return0val m = grid.size
val n = grid[0].size
var ans = 0val row = Array(m) { IntArray(n) }
val col = Array(m) { IntArray(n) }
for (i in0 until m) {
var cnt = 0for (j in0 until n) {
if (grid[i][j] =='W') cnt = 0elseif (grid[i][j] =='E') cnt++ row[i][j] = cnt
}
cnt = 0for (j in n - 1 downTo 0) {
if (grid[i][j] =='W') cnt = 0elseif (grid[i][j] =='E') cnt++ row[i][j] = maxOf(row[i][j], cnt)
}
}
for (j in0 until n) {
var cnt = 0for (i in0 until m) {
if (grid[i][j] =='W') cnt = 0elseif (grid[i][j] =='E') cnt++ col[i][j] = cnt
}
cnt = 0for (i in m - 1 downTo 0) {
if (grid[i][j] =='W') cnt = 0elseif (grid[i][j] =='E') cnt++ col[i][j] = maxOf(col[i][j], cnt)
}
}
for (i in0 until m) {
for (j in0 until n) {
if (grid[i][j] =='0')
ans = maxOf(ans, row[i][j] + col[i][j])
}
}
return ans
}
}
classSolution:
defmaxKilledEnemies(self, grid: list[list[str]]) -> int:
ifnot grid ornot grid[0]: return0 m, n = len(grid), len(grid[0])
ans =0 row = [[0]*n for _ in range(m)]
col = [[0]*n for _ in range(m)]
for i in range(m):
cnt =0for j in range(n):
if grid[i][j] =='W': cnt =0elif grid[i][j] =='E': cnt +=1 row[i][j] = cnt
cnt =0for j in range(n-1, -1, -1):
if grid[i][j] =='W': cnt =0elif grid[i][j] =='E': cnt +=1 row[i][j] = max(row[i][j], cnt)
for j in range(n):
cnt =0for i in range(m):
if grid[i][j] =='W': cnt =0elif grid[i][j] =='E': cnt +=1 col[i][j] = cnt
cnt =0for i in range(m-1, -1, -1):
if grid[i][j] =='W': cnt =0elif grid[i][j] =='E': cnt +=1 col[i][j] = max(col[i][j], cnt)
for i in range(m):
for j in range(n):
if grid[i][j] =='0':
ans = max(ans, row[i][j] + col[i][j])
return ans