forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bomb-enemy.cpp
50 lines (46 loc) · 1.51 KB
/
bomb-enemy.cpp
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
// Time: O(m * n)
// Space: O(m * n)
class Solution {
public:
int maxKilledEnemies(vector<vector<char>>& grid) {
int result = 0;
if (grid.empty() || grid[0].empty()) {
return result;
}
vector<vector<int>> down{grid.size(), vector<int>(grid[0].size())};
vector<vector<int>> right{grid.size(), vector<int>(grid[0].size())};
for (int i = grid.size() - 1; i >= 0; --i) {
for (int j = grid[0].size() - 1; j >= 0; --j) {
if (grid[i][j] != 'W') {
if (i + 1 < grid.size()) {
down[i][j] = down[i + 1][j];
}
if (j + 1 < grid[0].size()) {
right[i][j] = right[i][j + 1];
}
if (grid[i][j] == 'E') {
++down[i][j];
++right[i][j];
}
}
}
}
int left = 0;
vector<int> up(grid[0].size());
for (int i = 0; i < grid.size(); ++i) {
left = 0;
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j] == 'W') {
up[j] = 0;
left = 0;
} else if (grid[i][j] == 'E') {
++up[j];
++left;
} else {
result = max(result, left + up[j] + right[i][j] + down[i][j]);
}
}
}
return result;
}
};