Bomb Enemy

 1 public class Solution {
 2     public int maxKilledEnemies(char[][] grid) {
 3         if (grid.length == 0 || grid[0].length == 0) {
 4             return 0;
 5         }
 6         int result = 0;
 7         int rowCount = 0;
 8         int[] colCount = new int[grid[0].length];
 9 
10         for (int i = 0; i < grid.length; i++) {
11             for (int j = 0; j < grid[0].length; j++) {
12                 if (j == 0 || grid[i][j-1] == 'W') {
13                     rowCount = 0;
14                     for (int k = j; k < grid[0].length && grid[i][k] != 'W'; k++) {
15                         rowCount += grid[i][k] == 'E' ? 1 : 0;
16                     }
17                 }
18                 
19                 if (i == 0 || grid[i-1][j] == 'W') {
20                     colCount[j] = 0;
21                     for (int k = i; k < grid.length && grid[k][j] != 'W'; k++) {
22                         colCount[j] += grid[k][j] == 'E' ? 1 : 0;
23                     }
24                 }
25                 if (grid[i][j] == '0') {
26                     result = Math.max(result, rowCount + colCount[j]);;;
27                 }
28             }
29         }
30         return result;
31     }
32 }

 

Since the traversal is row by row. So the only one row count is enough.

Three conditions are:

1. j == 0 (new line start) or previous column is wall. Recalcuate the row count until end or meet wall.

2. i == 0 (starting row) or previous row is wall. Recalculate the column count untl end or meet wall

3. current val is "0", compare the result.

转载于:https://www.cnblogs.com/shuashuashua/p/5619742.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值