[Leetcode 361] Bomb Enemy

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)



Solution

顺序遍历,只需要用一个数值和一个数组row和col[]来保存当前killed enemies.

如果当前格子为'W', 说明之前保存的值无效,需要重新计算.

直接上代码:

 1 public int maxKilledEnemies(char[][] grid) {
 2    if(grid == null || grid.length == 0 ||  grid[0].length == 0) return 0;
 3    int max = 0;
 4    int row = 0;
 5    int[] col = new int[grid[0].length];
 6    for(int i = 0; i<grid.length; i++){
 7        for(int j = 0; j<grid[0].length;j++){
 8            if(grid[i][j] == 'W') continue;
 9            if(j == 0 || grid[i][j-1] == 'W'){
10                 row = killedEnemiesRow(grid, i, j);
11            }
12            if(i == 0 || grid[i-1][j] == 'W'){
13                 col[j] = killedEnemiesCol(grid,i,j);
14            }
15            if(grid[i][j] == '0'){
16                max = (row + col[j] > max) ? row + col[j] : max;
17            }
18        }
19 
20    }
21 
22    return max;
23 }
24 
25 //calculate killed enemies for row i from column j
26 private int killedEnemiesRow(char[][] grid, int i, int j){
27    int num = 0;
28    while(j <= grid[0].length-1 && grid[i][j] != 'W'){
29        if(grid[i][j] == 'E') num++;
30        j++;
31    }
32    return num;
33 }
34 //calculate killed enemies for  column j from row i
35 private int killedEnemiesCol(char[][] grid, int i, int j){
36    int num = 0;
37    while(i <= grid.length -1 && grid[i][j] != 'W'){
38        if(grid[i][j] == 'E') num++;
39        i++;
40    }
41    return num;
42 }

猜你喜欢

转载自www.cnblogs.com/xiatianhappy/p/10485097.html