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 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/6193701.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值