361. Bomb Enemy

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了361. 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:

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.

解题思路:

可以先对每一行中可放置炸弹的位置能够消灭的敌人进行统计。

然后在对每一列中可放置炸弹的位置能够消灭敌人的数量进行统计。

我之前的做法是遇到墙就更新上次遇到墙或者自开始以来能够放置炸弹的数量。

但是参考了user7468f的答案:这位大佬是先向左更新,再向右更新,写起来更加简洁明了一些。

 

代码:

class Solution 
public:
    int maxKilledEnemies(vector<vector<char>>& M) 
        if(!M.size()) return 0;
        if(!M[0].size()) return 0;
        
        int n, m, ans;
        n = M.size();
        m = M[0].size();
        vector<vector<int> > row(n, vector<int>(m, 0));
        vector<vector<int> > col(n, vector<int>(m, 0));
        
        ans = 0;
        
        for(int i=0; i<n; i++) 
            for(int j=0, cur=0; j<m; j++) 
                if(M[i][j] == W) cur = 0;
                else if(M[i][j] == E) cur++;
                else row[i][j] += cur;
            
            for(int j=m-1, cur=0; j>=0; j--) 
                if(M[i][j] == W) cur = 0;
                else if(M[i][j] == E) cur++;
                else row[i][j] += cur;
            
        
        
        for(int j=0; j<m; j++) 
            for(int i=0,cur=0; i<n; i++) 
                if(M[i][j] == W) cur = 0;
                else if(M[i][j] == E) cur++;
                else col[i][j] += cur;
            
            for(int i=n-1, cur=0; i>=0; i--) 
                if(M[i][j] == W) cur = 0;
                else if(M[i][j] == E) cur++;
                else col[i][j] += cur;
            
        
        
        for(int i=0; i<n; i++) for(int j=0; j<m; j++) ans = max(ans, row[i][j]+col[i][j]);
        return ans;
    
;

 

以上是关于361. Bomb Enemy的主要内容,如果未能解决你的问题,请参考以下文章

java 361. Bomb Enemy(1st).java

java 361. Bomb Enemy(1st).java

java 361. Bomb Enemy(1st).java

java 361. Bomb Enemy(1st).java

java 361. Bomb Enemy(1st).java

java 361. Bomb Enemy(1st).java