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,那么用一個變量數(shù)組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;
}
}