simple straightforward Java solution O(1) space


  • 0
    J

    idea is simple.
    If current place is 'X', and the left of it is '.' and the above of it is '.', count increase one.

        public int countBattleships(char[][] board) {
            if (board.length == 0 || board[0].length == 0) return 0;
            int cnt = 0;
            char last = '.';
            for (int i = 0; i < board[0].length; i++) {
                if (board[0][i] == 'X' && board[0][i] != last) cnt++;
                last = board[0][i];
            }
            for (int i = 1; i < board.length; i++) {
                last = '.';
                for (int j = 0; j < board[0].length; j++) {
                    if (board[i][j] == 'X' && board[i - 1][j] == '.' && last == '.') cnt++;
                    last = board[i][j];
                }
            }    
            return cnt;
        }
    

  • 0
    J

    @jobhunting88
    simplify a bit:

        public int countBattleships(char[][] board) {
            if (board.length == 0 || board[0].length == 0) return 0;
            int cnt = 0;
            for (int i = 0; i < board.length; i++) {
                int lastLeft = '.'; 
                for (int j = 0; j < board[0].length; j++) {
                    int lastUp = i == 0? '.' : board[i - 1][j];
                    if (board[i][j] == 'X' && lastUp == '.' && lastLeft == '.') cnt++;
                    lastLeft = board[i][j];
                }
            }    
            return cnt;
        }
    

Log in to reply
 

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