LeetCode 361: Bomb Enemy Solution

Master LeetCode problem 361 (Bomb Enemy), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

361. Bomb Enemy

Problem Explanation

Explanation:

To solve this problem, we can iterate over each cell of the grid and calculate the maximum number of enemies that can be killed by placing a bomb at that cell. For each cell, we can calculate the number of enemies that can be killed by the bomb placed in that cell by counting the number of enemies in the same row and column. We can then update the maximum number of enemies killed for that cell. :

Solution Code

class Solution {
    public int maxKilledEnemies(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        
        int m = grid.length;
        int n = grid[0].length;
        int result = 0;
        int rowCount = 0;
        int[] colCount = new int[n];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (j == 0 || grid[i][j - 1] == 'W') {
                    rowCount = 0;
                    for (int k = j; k < n && grid[i][k] != 'W'; k++) {
                        rowCount += grid[i][k] == 'E' ? 1 : 0;
                    }
                }
                
                if (i == 0 || grid[i - 1][j] == 'W') {
                    colCount[j] = 0;
                    for (int k = i; k < m && grid[k][j] != 'W'; k++) {
                        colCount[j] += grid[k][j] == 'E' ? 1 : 0;
                    }
                }
                
                if (grid[i][j] == '0') {
                    result = Math.max(result, rowCount + colCount[j]);
                }
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 361 (Bomb Enemy)?

This page provides optimized solutions for LeetCode problem 361 (Bomb Enemy) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 361 (Bomb Enemy)?

The time complexity for LeetCode 361 (Bomb Enemy) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 361 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 361 in Java, C++, or Python.

Back to LeetCode Solutions