361. Bomb Enemy - cocoder39/coco39_LC GitHub Wiki

361. Bomb Enemy

if (j == 0 || grid[i][j - 1] == 'W') 
if (i == 0 || grid[i - 1][j] == 'W')

idea is not difficult, but it is hard to code so concisely.

pay attention to time complexity which is O(m * n)

int maxKilledEnemies(vector<vector<char>>& grid) {
        int m = grid.size();
        if (m == 0) {
            return 0;
        }
        int n = grid[0].size();
        
        int res = 0;
        int rowhit;
        vector<int> colhit(n);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (j == 0 || grid[i][j - 1] == 'W') {
                    rowhit = 0;
                    //count hits for a range between two 'W's
                    for (int k = j; k < n && grid[i][k] != 'W'; k++) {
                        rowhit +=  grid[i][k] == 'E';
                    }
                } //otherwise, use previous rowhit
                
                if (i == 0 || grid[i - 1][j] == 'W') {
                    colhit[j] = 0;
                    for (int k = i; k < m && grid[k][j] != 'W'; k++) {
                        colhit[j] += grid[k][j] == 'E';
                    }
                }
                
                if (grid[i][j] == '0') {
                    res = max(res, rowhit + colhit[j]);
                }
            }
        }
        return res;
    }
⚠️ **GitHub.com Fallback** ⚠️