Bomb Enemy
row和col的缓存只会在(上/左)就是“W”时需要更新
因此初始化或者(上/左)是墙的时候,可以计算一个临时的结果,在遇到另一个'W'时停止
这个缓存在遇到新一个“上/左”是墙的鸽子之前,都是有效的,无需重复计算
考虑到循环row, col的顺序,我们的row只用cache一个变量,col需要cache一个数组
public class Solution {
public int maxKilledEnemies(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length;
int rowHits = 0, colHits[] = new int[n];
int max = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (j == 0 || grid[i][j - 1] == 'W') {
rowHits = 0;
for (int k = j; k < n && grid[i][k] != 'W'; k++) {
rowHits += grid[i][k] == 'E' ? 1 : 0;
}
}
if (i == 0 || grid[i - 1][j] == 'W') {
colHits[j] = 0;
for (int k = i; k < m && grid[k][j] != 'W'; k++) {
colHits[j] += grid[k][j] == 'E' ? 1 : 0;
}
}
if (grid[i][j] == '0') {
max = Math.max(max, rowHits + colHits[j]);
}
}
}
return max;
}
}