361 Bomb Enemy
361. Bomb Enemy
1. Question
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)2. Implementation
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[][] table = new int[m][n];
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '0') {
table[i][j] += getEnemies(i, j, grid, true);
table[i][j] += getEnemies(i, j, grid, false);
res = Math.max(res, table[i][j]);
}
}
}
return res;
}
public int getEnemies(int row, int col, char[][] grid, boolean isRow) {
int enemies = 0;
int i = row;
int j = col;
if (isRow) {
while (j < grid[0].length && grid[row][j] != 'W') {
if (grid[row][j] == 'E') {
++enemies;
}
++j;
}
j = col;
while (j >= 0 && grid[row][j] != 'W') {
if (grid[row][j] == 'E') {
++enemies;
}
--j;
}
}
else {
while (i < grid.length && grid[i][col] != 'W') {
if (grid[i][col] == 'E') {
++enemies;
}
++i;
}
i = row;
while (i >= 0 && grid[i][col] != 'W') {
if (grid[i][col] == 'E') {
++enemies;
}
--i;
}
}
return enemies;
}
}3. Time & Space Complexity
Last updated