Leetcode 419 Solution

This article provides solution to leetcode question 419 (battleships-in-a-board)

https://leetcode.com/problems/battleships-in-a-board

Solution

class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {
        if (board.size() == 0 || board[0].size() == 0)
            return 0;

        int m = board.size();
        int n = board[0].size();
        int total = 0;

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == 'X')
                {
                    if ((i == 0 || board[i - 1][j] == '.') && (j == 0 || board[i][j - 1] == '.'))
                        total++;
                }
            }
        }

        return total;
    }
};