Fork me on GitHub

Bomb Enemy

Description

https://leetcode.com/problems/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: You can only put the bomb at an empty cell.

Example:

1
2
3
4
5
6
7
8
9
Input: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
Output: 3
Explanation: For the given grid,

0 E 0 0
E 0 W E
0 E 0 0

Placing a bomb at (1,1) kills 3 enemies.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
int maxKilledEnemies(vector<vector<char>>& grid) {
int rowSize = grid.size();
if (rowSize == 0) return 0;
int columnSize = grid[0].size();
vector<vector<int>> rowFromLeft(rowSize, vector<int>(columnSize, 0));
vector<vector<int>> rowFromRight(rowSize, vector<int>(columnSize, 0));
vector<vector<int>> columnFromUp(rowSize, vector<int>(columnSize, 0));
vector<vector<int>> columnFromDown(rowSize, vector<int>(columnSize, 0));

vector<vector<int>> resultMatrix(rowSize, vector<int>(columnSize, 0));

for(int i = 0; i < rowSize; ++i) {
for(int j = 0; j < columnSize; ++j) {
if(grid[i][j] == '0') {
rowFromLeft[i][j] = (j > 0 ? rowFromLeft[i][j-1] : 0);
columnFromUp[i][j] = (i > 0 ? columnFromUp[i - 1][j] : 0);
resultMatrix[i][j] += rowFromLeft[i][j] + columnFromUp[i][j];
}

if(grid[i][j] == 'E') {
rowFromLeft[i][j] = (j > 0 ? rowFromLeft[i][j-1] + 1 : 1);
columnFromUp[i][j] = (i > 0 ? columnFromUp[i - 1][j] + 1 : 1);
}
//The wall case should be zero
}
}

for(int i = rowSize - 1; i >= 0; --i) {
for(int j = columnSize - 1; j >= 0; --j) {
if(grid[i][j] == '0') {
rowFromRight[i][j] = (j < columnSize-1 ? rowFromRight[i][j+1] : 0);
columnFromDown[i][j] = (i < rowSize-1 ? columnFromDown[i+1][j] : 0);
resultMatrix[i][j] += rowFromRight[i][j] + columnFromDown[i][j];
}

if(grid[i][j] == 'E') {
rowFromRight[i][j] = (j < columnSize-1 ? rowFromRight[i][j+1] + 1 : 1);
columnFromDown[i][j] = (i < rowSize-1 ? columnFromDown[i+1][j] + 1 : 1);
}
//The wall case should be zero
}
}
int ret = 0;
for(int i = 0; i < rowSize; ++i) {
for(int j = 0; j < columnSize; ++j) {
if (grid[i][j] == '0') ret = max(ret, resultMatrix[i][j]);
}
}
return ret;
}
};