zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    webservice的cxf的客户端
    webservice用cxf发布SOAP
    webservice声明发布SOAP1.2
    webservice使用注解修改WSDL内容
    webservice获取天气信息
    结巴分词原理介绍
    Pytorch学习记录-torchtext和Pytorch的实例( 使用神经网络训练Seq2Seq代码)
    【Pandas】Pandas求某列字符串的长度,总结经验教训
    UTF-8与UTF-8 BOM
    logging.basicConfig函数
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/11629302.html
Copyright © 2011-2022 走看看