3ms Clean Java Code with Explanation


  • 0
    A

    We go through each line and check each element. If it is 'X' and its upper element is not 'X' (if it has an upper element) we then increment counter by one. This is correct because of rule #2:
    Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.

    public class Solution {
        public int countBattleships(char[][] board) {
            int cnt = 0;
            if (board == null || board.length == 0 || board[0].length == 0) return cnt;
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (board[i][j] == 'X') {
                        if (i >= 1 && board[i - 1][j] == 'X') continue;
                        while (j + 1 < board[0].length && board[i][j + 1] == 'X') j++;
                        cnt++;
                    }
                }
            }
            return cnt;
        }
    }
    

Log in to reply
 

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