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.

Notice

You can only put the bomb at an empty cell.

Have you met this question in a real interview?

Yes

Example

Given a grid:

0 E 0 0
E 0 W E
0 E 0 0

return3. (Placing a bomb at (1,1) kills 3 enemies)

class Solution {
public:
    /**
     * @param grid Given a 2D grid, each cell is either 'W', 'E' or '0'
     * @return an integer, the maximum enemies you can kill using one bomb
     */
    int maxKilledEnemies(vector<vector<char>>& grid) {
        // Write your code here
        if (grid.empty() || grid[0].empty()) {
            return 0;
        }
        int n = grid.size(), m = grid[0].size();
        int rows = 0;
        vector<int> cols(m, 0);
        int res = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (j == 0 || grid[i][j - 1] == 'W') {
                    rows = 0;
                    for (int k = j; k < m && grid[i][k] != 'W'; ++k) {
                        if (grid[i][k] == 'E') {
                            ++rows;
                        }
                    }
                }
                if (i == 0 || grid[i - 1][j] == 'W') {
                    cols[j] = 0;
                    for (int k = i; k < n && grid[k][j] != 'W'; ++k) {
                        if (grid[k][j] == 'E') {
                            ++cols[j];
                        }
                    }
                }
                if (grid[i][j] == '0' && rows + cols[j] > res) {
                    res = rows + cols[j];
                }
            }
        }

        return res;
    }
};

results matching ""

    No results matching ""