3 line Java solution


  • 1
    J

    // Neat solution : (i > 0 && board[i-1][j] == 'X') means the element above i,j is a X. So we should NOT consider it as a separate ship. Similarly (j > 0 && board[i][j-1] == 'X') means element left to i,j is a X and again we should NOT consider it as a separate ship.

    public int countBattleships(char[][] board) {
       int count = 0;
       for(int i = 0 ; i < board.length; i++){
          for(int j = 0; j < board[i].length; j++){
             if(board[i][j] == 'X' && !(i > 0 && board[i-1][j] == 'X') && !(j > 0 && board[i][j-1] == 'X')){
                count++;
             }
          }
       }
       return count;
     }
    

    3 line ugly looking correct solution

    public int countBattleships(char[][] board) {
    int count = 0;
    for(int i = 0 ; i < board.length; i++)for(int j = 0; j < board[i].length; j++)if(board[i][j] == 'X' && !(i > 0 && board[i-1][j] == 'X') && !(j > 0 && board[i][j-1] == 'X')) count++;   
    return count;
     }
    

Log in to reply
 

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