Clean c++ solution


  • 1

    Suppose ship's head is on left or top side.
    Traverse left to right, top to down.
    Increment total number if we find the head.

    int countBattleships(vector<vector<char>>& board) {
            int size = board.size();
            int csize = size > 0 ? board[0].size() : 0;
            int count = 0;
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < csize; j++) {
                    if (board[i][j] == 'X' && !(i > 0 && board[i - 1][j] == 'X' || j > 0 && board[i][j - 1] == 'X')) {
                        count++;
                    }
                }
            }
            return count;
        }
    

Log in to reply
 

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