Simple Java O(mn) solution


  • 0
    S

    Plant a bomb at an empty cell. Go down and up, then right and left until there's a wall, and count enemies.

    public class Solution {
        public int maxKilledEnemies(char[][] grid) {
            int max = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == '0') {
                        max = Math.max(max, bomb(grid, i, j));
                    }
                }
            }
            return max;
        }
        
        private int bomb(char[][] grid, int row, int col) {
            int dead = 0;
            for (int i = row + 1; i < grid.length && grid[i][col] != 'W'; i++)
                if (grid[i][col] == 'E') dead++;
            for (int i = row - 1; i >= 0 && grid[i][col] != 'W'; i--)
                if (grid[i][col] == 'E') dead++;
            for (int j = col + 1; j < grid[0].length && grid[row][j] != 'W'; j++)
                if (grid[row][j] == 'E') dead++;
            for (int j = col - 1; j >= 0 && grid[row][j] != 'W'; j--)
                if (grid[row][j] == 'E') dead++;
            return dead;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.