zoukankan      html  css  js  c++  java
  • Leetcode: 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 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)

    Walk through the matrix. At the start of each non-wall-streak (row-wise or column-wise), count the number of hits in that streak and remember it.

    For the other positions, if it's still in the non-wall-streak(row-wise or col-wise), its hit has already been calculated.

    Once we meet 'W' in either row-wise or col-wise direction, we should recalculate the number of hits in that direction.

    O(mn) time, O(n) space.

     1 public class Solution {
     2     public int maxKilledEnemies(char[][] grid) {
     3         if (grid==null || grid.length==0 || grid[0].length==0) return 0;
     4         int row = 0;
     5         int[] col = new int[grid[0].length];
     6         int max = 0;
     7         for (int i=0; i<grid.length; i++) {
     8             for (int j=0; j<grid[0].length; j++) {
     9                 if (grid[i][j] == 'W') continue;
    10                 if (j==0 || grid[i][j-1]=='W') {
    11                     row = calcRowEnemy(grid, i, j);
    12                 } 
    13                 if (i==0 || grid[i-1][j]=='W') {
    14                     col[j] = calcColEnemy(grid, i, j);
    15                 }
    16                 if (grid[i][j] == '0') {
    17                     max = Math.max(max, row+col[j]);
    18                 }
    19             }
    20         }
    21         return max;
    22     }
    23     
    24     public int calcRowEnemy(char[][] grid, int i, int j) {
    25         int res = 0;
    26         while (j<grid[0].length && grid[i][j]!='W') {
    27             res = res + (grid[i][j]=='E'? 1 : 0);
    28             j++;
    29         }
    30         return res;
    31     }
    32     
    33     public int calcColEnemy(char[][] grid, int i, int j) {
    34         int res = 0;
    35         while (i<grid.length && grid[i][j]!='W') {
    36             res = res + (grid[i][j]=='E'? 1 : 0);
    37             i++;
    38         }
    39         return res;
    40     }
    41 }
  • 相关阅读:
    MTK 官方 openwrt SDK 使用
    PF_RING packet overwrites
    pycares cffi
    libevent evbuffer bug
    浮点转字符串性能比较
    重写 libev 的 EV_WIN32_HANDLE_TO_FD
    thrift TNonblockingServer 使用
    accel-pptp 部署
    boost::asio 使用 libcurl
    蜂鸟A20开发板刷 cubietruck 的 SD 卡固件
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6193701.html
Copyright © 2011-2022 走看看