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 }
  • 相关阅读:
    个性化推荐系统中的BadCase分析
    Hadoop优先级调度
    【剑指offer】斐波那契数列
    【剑指offer】旋转数组的最小数字
    【剑指offer】用两个栈实现队列
    【剑指offer】重建二叉树
    【剑指offer】从尾到头打印链表
    【剑指offer】替换空格
    【剑指offer】二维数组中的查找
    聚类算法项目整理
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6193701.html
Copyright © 2011-2022 走看看