码迷,mamicode.com
首页 > 其他好文 > 详细

361. Bomb Enemy

时间:2019-10-07 09:59:01      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:div   kill   位置   led   str   return   ble   sam   point   

问题描述:

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

标签:div   kill   位置   led   str   return   ble   sam   point   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/11629302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!