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)
一刷
题解:如果某个位置的左边是W,那么用一个变量rowCnt保存从左边的W到右边的W之间有多少E;如果某个位置的上边是W,那么用一个变量数组colCnt[i]保存列i从上边的W到下边的W之间有多少E;如果该位置是0(empty), 然后update max, max = Math.max(max, rowCnt + colCnt[i])
class Solution {
public int maxKilledEnemies(char[][] grid) {
if (grid.length == 0) return 0;
int m = grid.length, n = grid[0].length;
int max = 0, rowCnt = 0;
int [] colCnt = new int[n];
for (int i = 0; i < m; ++i) {
rowCnt = 0;
for (int j = 0; j < n; ++j) {
if (j == 0 || grid[i][j - 1] == 'W') {
rowCnt = 0;
for (int k = j; k < n && grid[i][k] != 'W'; ++k) {
if(grid[i][k] == 'E') rowCnt++ ;
}
}
if (i == 0 || grid[i - 1][j] == 'W') {
colCnt[j] = 0;
for (int k = i; k < m && grid[k][j] != 'W'; ++k) {
if( grid[k][j] == 'E') colCnt[j]++;
}
}
if (grid[i][j] == '0') {
max = Math.max(max, rowCnt + colCnt[j]);
}
}
}
return max;
}
}