Java solution


  • 0
    U
    public int countBattleships(char[][] board) {
        
        int count = 0;
        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[0].length; j++){
                if(isFirstX(board, i, j)){
                    count++;
                }
            }
        }
        return count;
    }
    
    public boolean isFirstX(char[][] board, int i, int j){
        if(board[i][j] != 'X'){
            return false;
        }
        if(i == 0 && j == 0){
            return true;
        }else if(i == 0){
            return board[i][j-1] != 'X';
        }else if(j == 0){
            return board[i-1][j] != 'X';
        }else{
            return board[i][j-1] != 'X' &&  board[i-1][j] != 'X';
        }
    }

Log in to reply
 

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