码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Bomb Enemy

时间:2017-09-28 09:54:31      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:java   ble   http   target   更新   logs   des   bom   res   

原题链接在这里: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 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)

题解:

DP问题. 要储存当前格子所在行和列遇到边界和墙之前能碰到的敌人个数. 用数组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 }

 

LeetCode Bomb Enemy

标签:java   ble   http   target   更新   logs   des   bom   res   

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/7604707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!