因此对于每一行,复杂度都是 O(cols),对于每一列,复杂度都是 O(rows),整个预处理的过程用时为 O(rows * cols),最后的扫描也是 P(rows * cols).
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 论坛上的解法:
public int maxKilledEnemies(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
int rows = grid.length;
int cols = grid[0].length;
int max = 0;
int rowCache = 0;
int[] colCache = new int[cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(j == 0 || grid[i][j - 1] == 'W'){
rowCache = 0;
for(int k = j; k < cols && grid[i][k] != 'W'; k++){
rowCache += grid[i][k] == 'E' ? 1 : 0;
}
}
if(i == 0 || grid[i - 1][j] == 'W'){
colCache[j] = 0;
for(int k = i; k < rows && grid[k][j] != 'W'; k++){
colCache[j] += grid[k][j] == 'E' ? 1 : 0;
}
}
if(grid[i][j] == '0') max = Math.max(max, rowCache + colCache[j]);
}
}
return max;
}