Java Sol easy to follow. Run time=2O(mn) space = O(mn)


  • 0
    C
    public int maxKilledEnemies(char[][] grid) {
            if(grid.length == 0 || grid[0].length == 0){
                return 0;
            }
            
            int len = grid.length, width = grid[0].length;
            
            int arr[][] = new int[len][width];
            
            for(int i=0; i<len; i++){
                int count = 0;
                
                // left to right
                for(int j=0; j<width; j++){
                    if(grid[i][j] == 'E'){
                        count++;
                    }
                    else if(grid[i][j] == '0'){
                        arr[i][j] += count;
                    }
                    else{
                        count = 0;
                    }
                }
                
                count = 0;
                
                // right to left 
                for(int j=width - 1; j>=0; j--){
                    if(grid[i][j] == 'E'){
                        count++;
                    }
                    else if(grid[i][j] == '0'){
                        arr[i][j] += count;
                    }
                    else{
                        count = 0;
                    }
                }
            }
            
            int max = 0;
            for(int j=0; j < width; j++){
                int count = 0;
                
                // from top to bottom
                for(int i=0; i<len; i++){
                    if(grid[i][j] == 'E'){
                        count++;
                    }
                    else if(grid[i][j] == '0'){
                        arr[i][j] += count;
                    }
                    else{
                        count = 0;
                    }
                }
                
                count = 0;
                
                // bottom to top
                for(int i=len - 1; i>=0; i--){
                    if(grid[i][j] == 'E'){
                        count++;
                    }
                    else if(grid[i][j] == '0'){
                        arr[i][j] += count;
                        max = Math.max(max, arr[i][j]);
                    }
                    else{
                        count = 0;
                    }
                }
            }
            
            return max;
        }
    

Log in to reply
 

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