zoukankan      html  css  js  c++  java
  • Bomb Enemy -- LeetCode

    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 that you can only put the bomb at an empty cell.

    Example:

    For the given grid
    
    0 E 0 0
    E 0 W E
    0 E 0 0
    
    return 3. (Placing a bomb at (1,1) kills 3 enemies)

    思路:扫描矩阵,用rowCount表示该点所在行内有多少敌人可见。用colCount[i]表示该点所在列i内有多少敌人可见。然后该点可见的敌人为两者之和。

    初始时两值为0.

    当我们位于行首或者该行上一格为墙,那么在该行向右扫描直到行尾或者遇见一堵墙,更新rowCount。

    当我们位于列首或者该列上一格为墙,那么在该列向下扫描直到列尾或者遇见一堵墙,更新colCount[i]。

    时间复杂度O(mn),空间复杂度O(N)。

     1 class Solution {
     2 public:
     3     int maxKilledEnemies(vector<vector<char>>& grid) {
     4         if (grid.size() == 0) return 0;
     5         int rowCount = 0, height = grid.size(), width = grid[0].size(), res = 0;
     6         vector<int> colCount(width, 0);
     7         for (int i = 0; i < height; i++) {
     8             for (int j = 0; j < width; j++) {
     9                 if (!j || grid[i][j-1] == 'W') {
    10                     rowCount = 0;
    11                     for (int k = j; k < width && grid[i][k] != 'W'; k++)
    12                         rowCount += grid[i][k] == 'E';
    13                 }
    14                 if (!i || grid[i-1][j] == 'W') {
    15                     colCount[j] = 0;
    16                     for (int k = i; k < height && grid[k][j] != 'W'; k++)
    17                         colCount[j] += grid[k][j] == 'E';
    18                 }
    19                 if (grid[i][j] == '0')
    20                     res = std::max(res, rowCount + colCount[j]);
    21             }
    22         }
    23         return res;
    24     }
    25 };
  • 相关阅读:
    python基础练习:
    py+selenium切换到新弹出窗口通用方法
    Python 异常处理
    验证码自动化认证部分,可能由于分辨率导致截图不正确
    基于Tesseract的OCR图像识别
    Spark相关知识
    Hive和数据库除了拥有类似的查询语言,再无类似之处;关系型数据库和非关系型数据库的优缺点
    sed替换^A(01),02,03等特殊字符
    Python操作adb命令脚本
    python从放弃到放弃
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5816608.html
Copyright © 2011-2022 走看看