Easy to read, 1-pass solution


  • -1

    Check to see if we've already counted the cells we passed to the left and above us.

        private static final char BATTLESHIP = 'X';
        
        public int countBattleships(char[][] board) {
            int count = 0;
            
            for (int row = 0; row < board.length; row++) {
                for (int col = 0; col < board[0].length; col++) {
                    if (shouldCount(row, col, board)) count++;
                }
            }
            
            return count;
        }
        
        private boolean shouldCount(int row, int col, char[][] board) {
            return hasBattleship(row, col, board)
                && !hasBattleship(row - 1, col, board)
                && !hasBattleship(row, col - 1, board);
        }
        
        private boolean hasBattleship(int row, int col, char[][] board) {
            if (row < 0) return false;
            if (col < 0) return false;
            return board[row][col] == BATTLESHIP;
        }
    

Log in to reply
 

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