Problem Description
You are given an m x n grid where each cell is either a wall 'W', an enemy 'E', or an empty cell '0'. When you place a bomb in an empty cell, it kills all enemies in the same row and column until a wall is encountered. Return the maximum number of enemies you can kill with one bomb.
Key Insights
- Instead of brute-forcing every empty cell and scanning its row and column each time, we can reuse counts.
- Use a running count for the current row segment (reset when a wall is encountered).
- Use an array to store column counts, recomputing the count only when the cell above is a wall.
- This dynamic programming-like approach allows updating counts only when necessary, reducing redundant computations.
Space and Time Complexity
Time Complexity: O(m * n) Space Complexity: O(n) (for the column count array)
Solution
We scan the grid once. For each cell, if it is at the beginning of a row segment (first column or left neighbor is a wall), we re-calculate the number of enemies to the right until a wall is met. Similarly, for columns, if the cell is at the beginning of a column segment (first row or top neighbor is a wall), we re-calculate the number of enemies downward until a wall is met. For empty cells '0', we sum the row and column counts to see if this location yields a higher kill count. This method leverages caching to avoid repeated work and efficiently computes the result in one pass.