Bomb Enemy
Description
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)
Hint
Train of Thought
对每一个炸弹, 都去check它能引爆的enemy的话, 太浪费时间, 因为会有很多重复搜索
如何能只遍历一遍就能知道answer?
每一行和每一列能被引爆的最大enemy数量存下来, 如果碰到Wall, 就重新计算, 这样按照先行后列的顺序遍历, 只用存一个row和col[grid[0].length], 碰到炸弹的时候, 直接把两个已经计算好的值相加就可以了.
Code
public class Solution {
public int maxKilledEnemies(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length;
int rowCache = 0;
int[] colCache = new int[n];
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
//if it is the first element, start calculate, if meets wall, recalculate
if (j == 0 || grid[i][j - 1] == 'W') {
rowCache = 0;
for (int k = j; k < n && 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 < m && grid[k][j] != 'W'; k++) {
colCache[j] += grid[k][j] == 'E' ? 1 : 0;
}
}
//if meets a bomb, use the current cache
if (grid[i][j] == '0') {
res = Math.max(res, rowCache + colCache[j]);
}
}
}
return res;
}
}