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)

分析:
建立四个累加数组v1, v2, v3, v4,其中v1是水平方向从左到右的累加数组,v2是水平方向从右到左的累加数组,v3是竖直方向从上到下的累加数组,v4是竖直方向从下到上的累加数组,
我们建立好这个累加数组后,对于任意位置(i, j),其可以炸死的最多敌人数就是v1[i][j] + v2[i][j] + v3[i][j] + v4[i][j],最后我们通过比较每个位置的累加和,就可以得到结果。
 1 public 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, n = grid[0].length, res = 0;
 8         int[][] v1 = new int[m][n];
 9         int[][] v2 = new int[m][n];
10         int[][] v3 = new int[m][n];
11         int[][] v4 = new int[m][n];
12         for (int i = 0; i < m; ++i) {
13             for (int j = 0; j < n; ++j) {
14                 int t = (j == 0 || grid[i][j] == 'W') ? 0 : v1[i][j - 1];
15                 v1[i][j] = grid[i][j] == 'E' ? t + 1 : t;
16             }
17             for (int j = n - 1; j >= 0; --j) {
18                 int t = (j == n - 1 || grid[i][j] == 'W') ? 0 : v2[i][j + 1];
19                 v2[i][j] = grid[i][j] == 'E' ? t + 1 : t;
20             }
21         }
22         for (int j = 0; j < n; ++j) {
23             for (int i = 0; i < m; ++i) {
24                 int t = (i == 0 || grid[i][j] == 'W') ? 0 : v3[i - 1][j];
25                 v3[i][j] = grid[i][j] == 'E' ? t + 1 : t;
26             }
27             for (int i = m - 1; i >= 0; --i) {
28                 int t = (i == m - 1 || grid[i][j] == 'W') ? 0 : v4[i + 1][j];
29                 v4[i][j] = grid[i][j] == 'E' ? t + 1 : t;
30             }
31         }
32         for (int i = 0; i < m; ++i) {
33             for (int j = 0; j < n; ++j) {
34                 if (grid[i][j] == '0') {
35                     res = Math.max(res, v1[i][j] + v2[i][j] + v3[i][j] + v4[i][j]);
36                 }
37             }
38         }
39         return res;
40     }
41 }

 

上一篇:python项目:飞机大战(爆炸效果,血条,音效,buff加成,boss,菜单,完整详细注释的源码)


下一篇:基础面向对象