Bomb Enemy Leetcode

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)

 

这道题按照先行后列的形式遍历,所以可以用一个变量存储每一行可以杀死的敌人的数量。但是要用一个数组把每一列可以杀死的敌人的数量存起来以供后面的行数用。

遍历每一行的时候,在一开始把这一行可以杀死的敌人的数量就算好,如果遇到墙或者到行尾了就停止。所以计算条件是行首或者左边是墙。

每一列的逻辑也是如此。

public class Solution {
    public int maxKilledEnemies(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int row = 0;
        int max = 0;
        int[] col = new int[grid[0].length];
        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 = getRowNumber(grid, i, j);
                }
                if (i == 0 || grid[i - 1][j] == 'W') {
                    col[j] = getColNumber(grid, i, j);
                }
                if (grid[i][j] == '0') {
                    max = row + col[j] > max ? row + col[j] : max;
                }
            }
        }
        return max;
    }
    private int getRowNumber(char[][] grid, int i, int j) {
        int count = 0;
        for (int k = j; k < grid[i].length; k++) {
            if (grid[i][k] == 'W') {
                break;
            }
            if (grid[i][k] == 'E') {
                count++;
            }
        }
        return count;
    }
    private int getColNumber(char[][] grid, int i, int j) {
        int count = 0;
        for (int k = i; k < grid.length; k++) {
            if (grid[k][j] == 'W') {
                break;
            }
            if (grid[k][j] == 'E') {
                count++;
            }
            
        }
        return count;
    }
}

期间犯了一个错误,看到是E就continue了是不对的,这个时候需要计算行列的E的数量呢。

但是遇到W是可以跳过的,没有影响。

没有自己直接做出来,后面还是回顾一下吧。。。

posted @ 2017-03-05 06:05  璨璨要好好学习  阅读(164)  评论(0编辑  收藏  举报