zoukankan      html  css  js  c++  java
  • LeetCode 361. Bomb Enemy

    原题链接在这里:https://leetcode.com/problems/bomb-enemy/description/

    题目:

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

    Example:

    Input: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
    Output: 3 
    Explanation: For the given grid,
    0 E 0 0 
    E 0 W E 
    0 E 0 0
    Placing a bomb at (1,1) kills 3 enemies.

    题解:

    DP问题. 要储存当前格子所在行和列能看到的敌人个数. 就拿两排array 来计数. 当遇到边界或者墙,就需要重新计算.

    用数组colHits储存列的. 因为行的更新和指针是同向移动的,所以用一个number就可以. 

    递推时, 在遇到墙和边界时清零重算, 否则敌人数目不变.

    起始值都是0. 

    Time Complexity: O(m*n). m = grid.length, n = grid[0].length. 每个格子至多走两边.

    Space: O(n). 可选m 和n中较小的.

    AC Java:

     1 class Solution {
     2     public int maxKilledEnemies(char[][] grid) {
     3         if(grid == null || grid.length == 0 || grid[0].length == 0){
     4             return 0;
     5         }
     6         
     7         int m = grid.length;
     8         int n = grid[0].length;
     9         
    10         int res = 0;
    11         int [] colHits = new int[n];
    12         int rowHits = 0;
    13         
    14         for(int i = 0; i<grid.length; i++){
    15             for(int j = 0; j<grid[0].length; j++){
    16                 if(i==0 || grid[i-1][j]=='W'){
    17                     colHits[j] = 0;
    18                     for(int k = i; k<m&&grid[k][j]!='W'; k++){
    19                         colHits[j] += (grid[k][j] == 'E' ? 1 : 0);
    20                     }
    21                 }
    22                 
    23                 if(j==0 || grid[i][j-1]=='W'){
    24                     rowHits = 0;
    25                     for(int k = j; k<n&&grid[i][k]!='W'; k++){
    26                         rowHits += (grid[i][k] == 'E' ? 1 : 0);
    27                     }
    28                 }
    29                 
    30                 if(grid[i][j] == '0'){
    31                     res = Math.max(res, rowHits + colHits[j]);
    32                 }
    33             }
    34         }
    35         
    36         return res;
    37     }
    38 }
  • 相关阅读:
    redis集群方式
    缓存数据库redis相关问题
    mybatis中如何进行多表关联查询
    mabaits出现parma不匹配时 或者参数>number 4 ,解决方法。
    El表达式
    Jsp概述
    Session会话技术
    springMVC之DateSource提示com.mysql.jdbc.Driver找不到
    Oracle查询死锁
    Mybatis 向oracle批量插入与更新数据
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7604707.html
Copyright © 2011-2022 走看看