One-pass, O(1) extra memory, and without modifying board


  • 0
    J
    int countBattleships(vector<vector<char>>& board) {
            int ans = 0, r = board.size(), c = r == 0 ? 0 : board[0].size();
            
            for(int i = 0; i < r; i++) {
                for(int j = 0; j < c; j++) {
                    if(board[i][j] == 'X') {
                        if(i == 0 || board[i - 1][j] != 'X') ans++;
                        while(j + 1 < c && board[i][j + 1] == 'X') j++;
                    }
                }
            }
            
            return ans;
        }
    

Log in to reply
 

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