Bomb Enemy
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)
Tips:
O(mn):
I think it is O(m * n). Although there is another for loop k inside for loops of i and j. It just calculates the enemies in advance. In the end, it will traverse this grid once to compute the enemies that are killed.
Every O(mn) algorithm is also O(mn*(m+n))
- 需要一个row变量,用来记录到下一个墙之前的敌人个数。还需要一个数组col,其中col[j]表示第j列到下一个墙之前的敌人个数。
- 算法思路是遍历整个数组grid,对于一个位置grid[i][j],对于水平方向,如果当前位置是开头一个或者前面一个是墙壁,我们开始从当前位置往后遍历,遍历到末尾或者墙的位置停止,计算敌人个数。对于竖直方向也是同样,如果当前位置是开头一个或者上面一个是墙壁,我们开始从当前位置向下遍历,遍历到末尾或者墙的位置停止,计算敌人个数。
- 有了水平方向和竖直方向敌人的个数,那么如果当前位置是0,表示可以放炸弹,我们更新结果res即可.
Code:
public class Solution {
public int maxKilledEnemies(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int max = 0;
int row = 0;
int[] col = new int[grid[0].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 'W') continue;
int m = i, n = j;
if (j == 0 || grid[i][j - 1] == 'W') {
row = 0;
while (n < grid[0].length && grid[m][n] != 'W') {
if (grid[m][n] == 'E') row++;
n++;
}
}
m = i; n = j;
if (i == 0 || grid[i - 1][j] == 'W') {
col[j] = 0;
while (m < grid.length && grid[m][n] != 'W') {
if (grid[m][n] == 'E') col[j]++;
m++;
}
}
if (grid[i][j] == '0') max = Math.max(max, row + col[j]);
}
}
return max;
}
}
别人版
public class Solution {
public int maxKilledEnemies(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int max = 0;
int row = 0;
int[] col = new int[grid[0].length];
for(int i = 0; i<grid.length; i++){
for(int j = 0; j<grid[0].length;j++){
if(grid[i][j] == 'W') continue;
if(j == 0 || grid[i][j-1] == 'W'){
row = killedEnemiesRow(grid, i, j);
}
if(i == 0 || grid[i-1][j] == 'W'){
col[j] = killedEnemiesCol(grid,i,j);
}
if(grid[i][j] == '0'){
max = (row + col[j] > max) ? row + col[j] : max;
}
}
}
return max;
}
//calculate killed enemies for row i from column j
private int killedEnemiesRow(char[][] grid, int i, int j){
int num = 0;
while(j <= grid[0].length-1 && grid[i][j] != 'W'){
if(grid[i][j] == 'E') num++;
j++;
}
return num;
}
//calculate killed enemies for column j from row i
private int killedEnemiesCol(char[][] grid, int i, int j){
int num = 0;
while(i <= grid.length -1 && grid[i][j] != 'W'){
if(grid[i][j] == 'E') num++;
i++;
}
return num;
}
}