C++ 5 liner, 1 Pass, No modification of board, O(n);


  • 0
    F
    struct Solution {
        int countBattleships(vector<vector<char>>& board) {
            int count = 0;
            for (int i = 0; i < board.size(); ++i)
                for (int j = 0; j < board[i].size(); ++ j) // only detect the "head" of the ship
                    count += board[i][j] == 'X' && (i - 1 < 0 || board[i - 1][j] == '.') && (j - 1 < 0 || board[i][j - 1] == '.');
            return count;
        }
    };
    

Log in to reply
 

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