361. Bomb Enemy

Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb.
The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed.
Note that you can only put the bomb at an empty cell.

Example:
For the given grid
0 E 0 0
E 0 W E
0 E 0 0
return 3. (Placing a bomb at (1,1) kills 3 enemies)

Solution:

思路:
遍历整个数组grid,对于一个位置grid[i][j],对于水平方向,如果当前位置是开头一个或者前面一个是墙壁,相当于重新计算:从当前位置往后遍历,遍历到末尾或者墙的位置停止,计算敌人个数。对于竖直方向也是同样,如果当前位置是开头一个或者上面一个是墙壁,我们开始从当前位置向下遍历,遍历到末尾或者墙的位置停止,计算敌人个数。
Time Complexity: O(mn) Space Complexity: O(n)

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 max = 0;
        
        int[] col_hits = new int[n]; // for one row
        int row_hits = 0;
        
        
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 'W') continue;
                if(j == 0 || grid[i][j - 1] == 'W') {
                     row_hits = killedEnemiesRow(grid, i, j);
                }
                if(i == 0 || grid[i - 1][j] == 'W') {
                     col_hits[j] = killedEnemiesCol(grid, i, j);
                }
                if(grid[i][j] == '0') {
                    int cur_hits = row_hits + col_hits[j];
                    if(cur_hits > max) {
                        max = cur_hits;
                    }
                }
            }

        }

        return max;
    }

    // count killed enemies for row i from column j
    private int killedEnemiesRow(char[][] grid, int i, int j){
        int num = 0;
        while(j <= grid[0].length - 1 && grid[i][j] != 'W'){
            if(grid[i][j] == 'E') num++;
            j++;
        }
        return num;
    }
    // count killed enemies for column j from row i
    private int killedEnemiesCol(char[][] grid, int i, int j){
        int num = 0;
        while(i <= grid.length -1 && grid[i][j] != 'W'){
            if(grid[i][j] == 'E') num++;
            i++;
        }
        return num;
    }
}

你可能感兴趣的:(361. Bomb Enemy)