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)
Credits:Special thanks to @memoryless for adding this problem and creating all test cases.
Solution
public class Solution {
public int maxKilledEnemies(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int row = grid.length;
int column = grid[0].length;
int[][] numbers = new int[row][column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (grid[i][j] == 'E') {
int up = i - 1;
while (up >= 0 && grid[up][j] != 'W') {
numbers[up][j] += 1;
up--;
}
up = i + 1;
while (up < row && grid[up][j] != 'W') {
numbers[up][j] += 1;
up++;
}
up = j - 1;
while (up >= 0 && grid[i][up] != 'W') {
numbers[i][up] += 1;
up--;
}
up = j + 1;
while (up < column && grid[i][up] != 'W') {
numbers[i][up] += 1;
up++;
}
}
}
}
int result = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (grid[i][j] != 'E') {
result = Math.max(result, numbers[i][j]);
}
}
}
return result;
}
}