Lintcode 553. 炸弹袭击 题解

描述

给一个二维矩阵, 每一个格子都可能是一堵墙 W, 一个敌人 E 或者空 0 (数字 '0'), 返回你可以用一个炸弹杀死的最大敌人数. 炸弹会杀死所有在同一行和同一列没有墙阻隔的敌人, 因为墙比较坚固难以摧毁.

样例

给一个矩阵:

0 E 0 0
E 0 W E
0 E 0 0

返回 3.(在(1, 1)处放炸弹可以杀死 3 个敌人)

 

思路:很简单就能有思路,在每个空闲的点往上下左右搜索就可以了,不过考虑到可能进行的重复搜索,这种显而易见的解法效率并不高,时间复杂度约为O(mn(m+n))

   我的做法是通过一个cache矩阵存储中间信息,从上下左右四个方向往中间扫描,累加能够炸死的Enemy,差不多就是空间换时间的想法吧。时间复杂度应该是O(mn)。

     下面附上AC代码:

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 height = grid.size();
        if(!height) return 0;
        int width = grid[0].size();
        if(!width) return 0;
        
        vector<vector<int>> cache(height,vector<int>(width,0));
        for(int y = 0; y < height; ++y){    //左右方向enemy计数
            int temp1 = 0;
            int temp2 = 0;
            for(int x = 0;x < width; ++x){
                
                if(grid[y][x] == 'E') ++temp1;      //具体这个方向上的enemy计算只需简单判断一下就可以了
                else if(grid[y][x] == '0') cache[y][x] += temp1;
                else temp1 = 0;
                
                if(grid[y][width - x - 1] == 'E') ++temp2;
                else if(grid[y][width - x - 1] == '0') cache[y][width - x - 1] += temp2;
                else temp2 = 0;
            }
        }
        
        for(int x = 0;x < width; ++x){    //上下方向enemy计数
            int temp1 = 0;
            int temp2 = 0;
            for(int y = 0;y < height; ++y){
                if(grid[y][x] == 'E') ++temp1;
                else if(grid[y][x] == '0') cache[y][x] += temp1;
                else temp1 = 0;
                
                if(grid[height - y - 1][x] == 'E') ++temp2;
                else if(grid[height - y - 1][x] == '0') cache[height - y - 1][x] += temp2;
                else temp2 = 0;
            }
        }
        int res = 0;
        for(int y = 0; y < height; ++y){
            for(int x = 0; x < width; ++x){
          if(grid[y][x] == '0')   res
= max(res,cache[y][x]); } } return res; } };

 

转载于:https://www.cnblogs.com/J1ac/p/9082789.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值