dp
分别计算从左到右、从右到左、从上到下、从下到上4个方向可能的值,然后计算所有为‘0’的地方的4个方向的值的最大值
https://www.cnblogs.com/grandyang/p/5599289.html
class Solution {
public:
/**
* @param grid: Given a 2D grid, each cell is either 'W', 'E' or '0'
* @return: an integer, the maximum enemies you can kill using one bomb
*/
int maxKilledEnemies(vector<vector<char> > &grid) {
// write your code here
int m = grid.size();
if(m <= )
return ;
int n = grid[].size();
if(n <= )
return ;
vector<vector<int> > left(m,vector<int>(n,)),right(m,vector<int>(n,)),top(m,vector<int>(n,)),down(m,vector<int>(n,));
for(int i = ;i < m;i++){
for(int j = ;j < n;j++){
int tmp;
if(j == || grid[i][j] == 'W')
tmp = ;
else
tmp = left[i][j-];
if(grid[i][j] == 'E')
left[i][j] = tmp + ;
else
left[i][j] = tmp;
}
}
for(int i = ;i < m;i++){
for(int j = n - ;j >= ;j--){
int tmp;
if(j == n - || grid[i][j] == 'W')
tmp = ;
else
tmp = right[i][j+];
if(grid[i][j] == 'E')
right[i][j] = tmp + ;
else
right[i][j] = tmp;
}
}
for(int j = ;j < n;j++){
for(int i = ;i < m;i++){
int tmp;
if(i == || grid[i][j] == 'W')
tmp = ;
else
tmp = top[i-][j];
if(grid[i][j] == 'E')
top[i][j] = tmp + ;
else
top[i][j] = tmp;
}
}
for(int j = ;j < n;j++){
for(int i = m-;i >= ;i--){
int tmp;
if(i == m- || grid[i][j] == 'W')
tmp = ;
else
tmp = down[i+][j];
if(grid[i][j] == 'E')
down[i][j] = tmp + ;
else
down[i][j] = tmp;
}
}
int max_num = ;
for(int i = ;i < m;i++){
for(int j = ;j < n;j++){
if(grid[i][j] == '')
max_num = max(max_num,left[i][j] + right[i][j] + top[i][j] + down[i][j]);
}
}
return max_num;
}
};