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)

S: 存储每行每列最多能炸到的敌人 O(MN)

存储每个行,列能炸到额enimies数目,只有上面或前面是‘W' 才重新计算

    int maxKilledEnemies(vector<vector<char>>& grid) {
        int m = grid.size();
        if (m < 1) return 0;
        int n = grid[0].size();
        int result = 0;
        int row = 0;
        vector<int> column(n, 0);
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 'W') continue;
                if (j == 0 || grid[i][j - 1] == 'W') { //第一列或前面是墙,重新计算此行enemy数
                    row = 0;
                    for (int k = j; k < n && grid[i][k] != 'W'; ++k) {
                        if (grid[i][k] == 'E') {
                            row++;
                        }
                    }
                }
                if (i == 0 || grid[i - 1][j] == 'W') {//第一行或上面是墙,重新计算此列enemy数
                {
                    column[j] = 0;
                    for (int k = i; k < m && grid[k][j] != 'W'; ++k) {
                        if (grid[k][j] == 'E') {
                            column[j]++;
                        }
                    }
                }
                if (grid[i][j] == '0') {
                    result = max(result, row + column[j]);
                }
            }
        }
        return result;
    }

results matching ""

    No results matching ""