Bomb Enemy - Problem

You are given an m x n matrix grid where each cell contains one of the following:

  • 'W' - represents a wall
  • 'E' - represents an enemy
  • '0' - represents an empty cell

You want to place a bomb in an empty cell that will kill the maximum number of enemies. The bomb kills all enemies in the same row and column from the bomb's position until it hits a wall, since walls are too strong to be destroyed.

Return the maximum number of enemies you can kill with one bomb.

Input & Output

Example 1 — Basic Grid
$ Input: grid = [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
Output: 3
💡 Note: Placing bomb at (1,1) kills 3 enemies: one to the left in same row, one above and one below in same column
Example 2 — Wall Blocking
$ Input: grid = [["0","0","0"],["E","W","E"],["0","0","0"]]
Output: 1
💡 Note: Wall blocks the bomb explosion, so maximum enemies killed is 1
Example 3 — No Empty Cells
$ Input: grid = [["W","E"],["E","W"]]
Output: 0
💡 Note: No empty cells available to place a bomb, so return 0

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 500
  • grid[i][j] is either '0', 'E', or 'W'

Visualization

Tap to expand
Bomb Enemy - Optimal Solution INPUT 3x4 Grid Matrix 0 E 0 0 E 0 W E 0 E 0 0 Legend: 0 = Empty E = Enemy W = Wall Bomb spot grid = [["0","E","0","0"], ["E","0","W","E"], ["0","E","0","0"]] ALGORITHM STEPS 1 Pre-compute Row Kills Count enemies in each row segment (between walls) 2 Pre-compute Col Kills Count enemies in each col segment (between walls) 3 Scan Empty Cells For each '0' cell, sum row_kills + col_kills 4 Track Maximum Keep max enemies killed across all empty cells Cell (1,1) Calculation: Row: E-->0-->W = 1 enemy Col: E-->0-->E = 2 enemies Total: 1 + 2 = 3 enemies FINAL RESULT 0 E 0 0 E W E 0 E 0 0 Maximum Enemies Killed: 3 OK - Optimal: O(mn) Bomb at (1,1) kills 3: Left E + Top E + Bottom E Key Insight: Pre-compute enemies killed for each row/column segment only when hitting a wall or starting a new row/column. This avoids redundant counting and reduces time from O(m*n*(m+n)) brute force to O(m*n) optimal solution. Walls act as blockers - bomb blast cannot penetrate walls, creating independent segments for counting. TutorialsPoint - Bomb Enemy | Optimal Solution
Asked in
Google 45 Facebook 38 Amazon 32
32.5K Views
Medium Frequency
~25 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen