Bomb Enemy
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
以上是关于Bomb Enemy的主要内容,如果未能解决你的问题,请参考以下文章