You are given a 2D grid representing a field with enemies ('E'), walls ('W'), and empty spaces ('0'). You can place a single bomb in any empty space. When the bomb explodes, it kills all enemies in its row and column until the blast hits a wall. The goal is to find the maximum number of enemies you can kill with one bomb.
This is a popular matrix-based Dynamic Programming problem at Google. It tests your ability to optimize redundant calculations. The naive approach (calculating the kill count for every empty cell by scanning its entire row and column) is . A better approach uses DP to cache the counts, reducing the complexity to .
This problem uses Dynamic Programming on a Matrix. The trick is to only recompute the "row kill count" when you start a new row or hit a wall, and to keep an array of "column kill counts" that you update when you start a new column or hit a wall. For each cell, the total kills is row_count + col_counts[j].
Grid: 0 E 0 E W E 0 E 0
The most common mistake is the inefficient approach. Another is getting the wall-blocking logic wrong—forgetting that a wall at (1,1) stops a bomb at (1,0) from hitting an enemy at (1,2). Finally, some candidates struggle with managing the state of the "current" row and column counts during a single pass.
When working with grid problems that involve "range" effects (like bombs or vision), look for ways to cache values that are shared across adjacent cells. If you can't solve it in one pass, try precomputing four DP tables: one for each direction (up, down, left, right).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Check if There is a Path With Equal Number of 0's And 1's | Medium | Solve | |
| Longest Line of Consecutive One in Matrix | Medium | Solve | |
| Minimum Path Cost in a Grid | Medium | Solve | |
| Maximum Non Negative Product in a Matrix | Medium | Solve | |
| Maximum Number of Moves in a Grid | Medium | Solve |