博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lintcode 553. 炸弹袭击 题解
阅读量:4692 次
发布时间:2019-06-09

本文共 2299 字,大约阅读时间需要 7 分钟。

描述

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

样例

给一个矩阵:

0 E 0 0E 0 W E0 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
> &grid) { // write your code here int height = grid.size(); if(!height) return 0; int width = grid[0].size(); if(!width) return 0; vector
> cache(height,vector
(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

你可能感兴趣的文章
win10应用UserControl
查看>>
Magento开发文档(二):Magento配置
查看>>
用递归的方法,判断某个字符串是否为回文
查看>>
[LeetCode] 100. Same Tree Java
查看>>
BZOJ4516: [Sdoi2016]生成魔咒(后缀自动机)
查看>>
查看手机已经记住的WIFI密码
查看>>
Linux实战教学笔记24:SSH连接原理及ssh-key
查看>>
最新版IntelliJ IDEA2019 破解教程(2019.08.07-情人节更新)
查看>>
Dynamic CRM 2013学习笔记(四十二)流程5 - 实时/同步工作流(Workflow)用法图解...
查看>>
Windows下命令(bat可用)
查看>>
我是怎么用缠论在商品里边抢钱之二 (2019-07-12 15:10:10)
查看>>
python入门之正则表达式
查看>>
SAS学习经验总结分享:篇五-过程步的应用
查看>>
Android创建文件夹及文件并写入数据
查看>>
file的getPath getAbsolutePath和getCanonicalPath的不同
查看>>
课时4—切入切出动画
查看>>
eclipse 编辑 python 中文乱码的解决方案
查看>>
Python 爬虫的集中简单方式
查看>>
数据库MySQL/mariadb知识点——触发器
查看>>
Ubuntu做Tomcat服务:insserv: warning: script 'tomcat' missing LSB tags and overrides
查看>>