题目描述:
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:
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.
class Solution {
public:
int maxKilledEnemies(vector<vector<char>>& grid) {
if(grid.size()==0||grid[0].size()==0) return 0;
int m=grid.size();
int n=grid[0].size();
vector<vector<int>> v1(m,vector<int>(n,0));
vector<vector<int>> v2(m,vector<int>(n,0));
vector<vector<int>> v3(m,vector<int>(n,0));
vector<vector<int>> v4(m,vector<int>(n,0));
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) { // v1[i][j]表示从(i,j)爆炸,向左消灭的敌人数
if(grid[i][j]=='W') continue;
if(grid[i][j]=='E') v1[i][j]++;
if(j>0) v1[i][j]+=v1[i][j-1];
}
for(int j=n-1;j>=0;j--) { // v2[i][j]表示从(i,j)爆炸,向右消灭的敌人数
if(grid[i][j]=='W') continue;
if(grid[i][j]=='E') v2[i][j]++;
if(j<n-1) v2[i][j]+=v2[i][j+1];
}
}
for(int j=0;j<n;j++) {
for(int i=0;i<m;i++) { // v3[i][j]表示从(i,j)爆炸,向上消灭的敌人数
if(grid[i][j]=='W') continue;
if(grid[i][j]=='E') v3[i][j]++;
if(i>0) v3[i][j]+=v3[i-1][j];
}
for(int i=m-1;i>=0;i--) { // v4[i][j]表示从(i,j)爆炸,向下消灭的敌人数
if(grid[i][j]=='W') continue;
if(grid[i][j]=='E') v4[i][j]++;
if(i<m-1) v4[i][j]+=v4[i+1][j];
}
}
int result=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]=='0')
result=max(result,v1[i][j]+v2[i][j]+v3[i][j]+v4[i][j]);
}
}
return result;
}
};