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 }
  • 相关阅读:
    C#获取windos 登录用户信息
    像我这样的人
    只道情深,奈何缘浅(雪之轻裳搜集)
    如果我死了,还剩下什么(雪之轻裳)
    嫁给爱情 还是嫁给现实(搜集)
    排名前 16 的 Java 工具类
    java 获取当前屏幕截图
    转:零售数据观(一):如何花30分钟成为一个标签设计“达人”
    转:数据指标系列:电商数据分析指标体系总结V1.0
    转:领域模型中的实体类分为四种类型:VO、DTO、DO、PO
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6193701.html
Copyright © 2011-2022 走看看