Brute Force solution with Java


  • 0
    M

    public int maxKilledEnemies(char[][] grid) {
    if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;

        int max = 0;
        int row = grid.length;
        int col = grid[0].length;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(grid[i][j] == '0') {
                    max= Math.max(max, getmaxene(i,j, grid));
                }
            }
        }
        return max;
    }
    public int getmaxene(int row, int col, char[][] grid) {
        int count = 0;
        int m = grid.length;
        int n = grid[0].length;
        for(int j = col -1; col-1>=0 && j >= 0; j--) {
            if(grid[row][j] == 'W') break;
            if(grid[row][j] == 'E') count++;
        }
        for(int i = row -1; row-1>=0 && i >= 0; i--) {
            if(grid[i][col] == 'W') break;
            if(grid[i][col] == 'E') count++;
        }
        for(int j = col+1; col+1<n && j<n; j++) {
            if(grid[row][j] == 'W') break;
            if(grid[row][j] == 'E') count++;
        }
        for(int i = row+1; row+1<m && i<m; i++) {
            if(grid[i][col] == 'W') break;
            if(grid[i][col] == 'E') count++;
        }
        return count;
    }

Log in to reply
 

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