A good Java solution


  • 0
    K

    See explanation below the code.

    public class Solution {
        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) {
                    char c = board[i][j];
                    if ((c == 'X') && 
                        (j == 0 || board[i][j - 1] != 'X') && 
                        (i == 0 || board[i - 1][j] != 'X')) {
                        count ++;
                    }
                }
            }
            
            return count;
        }
    }
    

    We traverse the 2-D array from the top-left corner and we increment the counter every time we encounter an X that isn't part of another ship. So, in order to increment the counter, all of the following conditions must be met:

    1. the current character must be an X (or else there would be no reason to believe there was a ship there)
    2. there can't be another X to the left of the current character (or else it would be a continuation of a ship we've already counted)
    3. there can't be another X above the current character (or else it would be a continuation of a ship we've already counted)

Log in to reply
 

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