Leetcode: Bomb Enemy

时间:2023-02-27 11:38:08
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)

Walk through the matrix. At the start of each non-wall-streak (row-wise or column-wise), count the number of hits in that streak and remember it.

For the other positions, if it's still in the non-wall-streak(row-wise or col-wise), its hit has already been calculated.

Once we meet 'W' in either row-wise or col-wise direction, we should recalculate the number of hits in that direction.

O(mn) time, O(n) space.

 public class Solution {
public int maxKilledEnemies(char[][] grid) {
if (grid==null || grid.length==0 || grid[0].length==0) return 0;
int row = 0;
int[] col = new int[grid[0].length];
int max = 0;
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 = calcRowEnemy(grid, i, j);
}
if (i==0 || grid[i-1][j]=='W') {
col[j] = calcColEnemy(grid, i, j);
}
if (grid[i][j] == '0') {
max = Math.max(max, row+col[j]);
}
}
}
return max;
} public int calcRowEnemy(char[][] grid, int i, int j) {
int res = 0;
while (j<grid[0].length && grid[i][j]!='W') {
res = res + (grid[i][j]=='E'? 1 : 0);
j++;
}
return res;
} public int calcColEnemy(char[][] grid, int i, int j) {
int res = 0;
while (i<grid.length && grid[i][j]!='W') {
res = res + (grid[i][j]=='E'? 1 : 0);
i++;
}
return res;
}
}