Bomb Enemies
public class Solution {
public int maxKilledEnemies(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
int rows = grid.length;
int cols = grid[0].length;
int[][] rowMax = new int[rows][cols];
int[][] colMax = new int[rows][cols];
for(int i = 0; i < rows; i++){
int[] count = new int[cols];
int enemyCount = 0;
for(int j = 0; j < cols; j++){
if(grid[i][j] == 'W') enemyCount = 0;
if(grid[i][j] == 'E') enemyCount ++;
count[j] = enemyCount;
}
int maxCount = 0;
for(int j = cols - 1; j >= 0; j--){
if(grid[i][j] == '0') {
maxCount = Math.max(maxCount, count[j]);
rowMax[i][j] = maxCount;
}
if(grid[i][j] == 'W') {
maxCount = 0;
rowMax[i][j] = 0;
}
if(grid[i][j] == 'E') {
maxCount = Math.max(maxCount, count[j]);
rowMax[i][j] = 0;
}
}
}
for(int i = 0; i < cols; i++){
int[] count = new int[rows];
int enemyCount = 0;
for(int j = 0; j < rows; j++){
if(grid[j][i] == 'W') enemyCount = 0;
if(grid[j][i] == 'E') enemyCount ++;
count[j] = enemyCount;
}
int maxCount = 0;
for(int j = rows - 1; j >= 0; j--){
if(grid[j][i] == '0') {
maxCount = Math.max(maxCount, count[j]);
colMax[j][i] = maxCount;
}
if(grid[j][i] == 'W') {
maxCount = 0;
colMax[j][i] = 0;
}
if(grid[j][i] == 'E') {
maxCount = Math.max(maxCount, count[j]);
colMax[j][i] = 0;
}
}
}
int max = 0;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
max = Math.max(max, rowMax[i][j] + colMax[i][j]);
}
}
return max;
}
}上面我第一次 AC 的代码能过,但是代码量略大,而且空间使用也不算经济。下面是参考 LC 论坛上的解法:
Last updated