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)

Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.

遍历整个数组,当i = 0或者grid[i][j - 1] = 'w'的时候需要重新计算右边的enemies,当j = 0或者grid[i - 1][j] = 'w'的时候需要重新计算下边的enemies,当grid[i][j] = '0'时,比较max和row+col的大小取较大,当grid[i][j] = 'w'时跳过这轮循环。代码如下:

public class Solution {
    public int maxKilledEnemies(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int row = 0;
        int[] col = new int[grid[0].length];
        int max = 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 = killRowEnemies(grid[i], j);
                }
                if (i ==0 || grid[i - 1][j] == 'W') {
                    col[j] = killColEnemies(grid, i, j);
                }
                if (grid[i][j] == '0') {
                    max = Math.max(max, row + col[j]);
                }
            }
        }
        return max;
    }
    
    private int killRowEnemies(char[] row, int index) {
        int num = 0;
        while (index < row.length && row[index] != 'W') {
            if (row[index] == 'E') {
                num ++;
            }
            index ++;
        }
        return num;
    } 
    
    private int killColEnemies(char[][] grid, int i, int j) {
        int num = 0;
        while (i < grid.length && grid[i][j] != 'W') {
            if (grid[i][j] == 'E') {
                num ++;
            }
            i ++;
        }
        return num;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值