Leetcode
Dynamic Programming
361 Bomb Enemy

361. Bomb Enemy

1. Question

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:
1
For the given grid
2
3
0 E 0 0
4
E 0 W E
5
0 E 0 0
6
7
return 3. (Placing a bomb at (1,1) kills 3 enemies)
Copied!

2. Implementation

(1) DP Brute Force
1
class Solution {
2
public int maxKilledEnemies(char[][] grid) {
3
if (grid == null || grid.length == 0 || grid[0].length == 0) {
4
return 0;
5
}
6
7
int m = grid.length, n = grid[0].length;
8
int[][] table = new int[m][n];
9
int res = 0;
10
11
for (int i = 0; i < m; i++) {
12
for (int j = 0; j < n; j++) {
13
if (grid[i][j] == '0') {
14
table[i][j] += getEnemies(i, j, grid, true);
15
table[i][j] += getEnemies(i, j, grid, false);
16
res = Math.max(res, table[i][j]);
17
}
18
}
19
}
20
return res;
21
}
22
23
public int getEnemies(int row, int col, char[][] grid, boolean isRow) {
24
int enemies = 0;
25
int i = row;
26
int j = col;
27
28
if (isRow) {
29
while (j < grid[0].length && grid[row][j] != 'W') {
30
if (grid[row][j] == 'E') {
31
++enemies;
32
}
33
++j;
34
}
35
36
j = col;
37
while (j >= 0 && grid[row][j] != 'W') {
38
if (grid[row][j] == 'E') {
39
++enemies;
40
}
41
--j;
42
}
43
}
44
else {
45
while (i < grid.length && grid[i][col] != 'W') {
46
if (grid[i][col] == 'E') {
47
++enemies;
48
}
49
++i;
50
}
51
52
i = row;
53
54
while (i >= 0 && grid[i][col] != 'W') {
55
if (grid[i][col] == 'E') {
56
++enemies;
57
}
58
--i;
59
}
60
}
61
return enemies;
62
}
63
}
Copied!
(2) DP Optimized
1
class Solution {
2
public int maxKilledEnemies(char[][] grid) {
3
if (grid == null || grid.length == 0 || grid[0].length == 0) {
4
return 0;
5
}
6
7
int m = grid.length, n = grid[0].length;
8
int res = 0;
9
int rowHits = 0;
10
int[] colHits = new int[n];
11
12
for (int i = 0; i < m; i++) {
13
for (int j = 0; j < n; j++) {
14
if (j == 0 || grid[i][j - 1] == 'W') {
15
rowHits = 0;
16
for (int k = j; k < n && grid[i][k] != 'W'; k++) {
17
if (grid[i][k] == 'E') {
18
++rowHits;
19
}
20
}
21
}
22
23
if (i == 0 || grid[i - 1][j] == 'W') {
24
colHits[j] = 0;
25
for (int k = i; k < m && grid[k][j] != 'W'; k++) {
26
if (grid[k][j] == 'E') {
27
++colHits[j];
28
}
29
}
30
}
31
32
if (grid[i][j] == '0') {
33
res = Math.max(res, rowHits + colHits[j]);
34
}
35
}
36
}
37
return res;
38
}
39
}
Copied!

3. Time & Space Complexity

DP Brute Force: 时间复杂度O(mn(m + n)), 空间复杂度O(mn)
DP Optimized: 时间复杂度O(mn), 空间复杂度O(n)