Java easy follow up solution with explanation

  • 0

    Since every battleships are separated by '.' and the "width" of the ships is always 1, we just need check if the previous cell of current 'X' cell in x and y direction is 'X' or not. And always count the first cell with 'X'. If previous cell is 'X', that means current 'X' belongs to the previous one which has already been counted.

    public int countBattleships(char[][] board) {
        int count = 0;
        int m = board.length;
        int n = board[0].length;
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                    else count++;
        return count;

Log in to reply

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