5 line simplest Java solution


  • 0
    F

    In some other problems like Number of Islands etc, we need to traverse all the neighbors of a cell so we do a dfs/bfs. This problem is much simpler. The battleship can only be vertical line or horizontal line and they will be separated by atleast a cell in a valid board.
    So if we find a cell with 'X', it's sufficient to just check if it's left cell and top cell is not 'X' (which would mean it's a part of a battleship already counted previously, since we are traversing the matrix left to right, top to bottom)

    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(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.