Bomb Enemy solution


  • 0
    T
    class Solution {
        public int maxKilledEnemies(char[][] grid) {
            if(grid.length == 0){
                return 0;
            }
            int maxKill = 0;
            int row = grid.length;
            int col = grid[0].length;
            Position[][] pos = new Position[row][col];
            for(int i=0; i<row; i++){
                for(int j=0; j<col; j++){
                    pos[i][j] = new Position();
                    if(grid[i][j] == 'W'){
                        continue;
                    }
                    pos[i][j].top = (i == 0?0:pos[i-1][j].top)+(grid[i][j] == 'E'?1:0);
                    pos[i][j].left = (j == 0?0:pos[i][j-1].left)+(grid[i][j] == 'E'?1:0);
                }
            }
            
            for(int i=row-1; i>=0; i--){
                for(int j=col-1; j>=0; j--){
                    if(grid[i][j] == 'W'){
                        continue;
                    }
                    pos[i][j].right = (j == col-1?0:pos[i][j+1].right) + (grid[i][j] == 'E'?1:0);
                    pos[i][j].bottom = (i == row-1?0:pos[i+1][j].bottom) + (grid[i][j] == 'E'?1:0);
                    
                    if(grid[i][j] == '0'){
                        maxKill = Math.max(maxKill, pos[i][j].top+pos[i][j].left+pos[i][j].right+pos[i][j].bottom);
                    }
                }
            }
            return maxKill;
        }
    }
    
    class Position{
        int top;
        int left;
        int right;
        int bottom;
        public Position(){
            this.top = 0;
            this.left = 0;
            this.right = 0;
            this.bottom = 0;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.