yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #361. Bomb Enemy #278

Open yokostan opened 5 years ago

yokostan commented 5 years ago
public class Solution {
    public int maxKilledEnemies(char[][] grid) {
        if(grid== null || grid.length == 0 || grid[0].length==0) return 0; 
        int n = grid.length; 
        int m = grid[0].length; 
        int res = 0;
        int rowhits = 0;
        int[] colhits = new int[m];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (j == 0 || grid[i][j - 1] == 'W') {
                    rowhits = 0;
                    for (int k = j; k < m && grid[i][k] != 'W'; k++) {
                        if (grid[i][k] == 'E') rowhits += 1;
                    }
                }
                if (i == 0 || grid[i - 1][j] == 'W') {
                    colhits[j] = 0;
                    for (int k = i; k < n && grid[k][j] != 'W'; k++) {
                        if (grid[k][j] == 'E') colhits[j] += 1;  
                    }
                }
                if (grid[i][j] == '0') {
                    res = Math.max(res, rowhits + colhits[j]);
                }
            }
        }
        return res;
    }
}