LeetCode 419. Battleships in a Board: C++ Solution

Problem Statement

Given an 2D board, count the total number of battleships on it.

Battleships are represented by ‘X’s,

Board slots without a battleship are represented by ‘.’s.

Assume that you have a valid board. Every spot is empty or contains a battleship.

Battleships can only be placed vertically or horizontally.

No two battleships are adjacent. Assume there’s at least one space between each battleship.

``````Function Signature (C++):
int countBattleships(vector<vector<char>>& board)

Inputs:
X..X
...X
...X

Outputs:
2

Inputs:
...X
XXXX
...X

Invalid board - adjacent battleships.
``````

TL;DR Code Solution

``````bool isTopLeft(vector<vector<char>>& board, int i, int j) {

bool leftMost = false;
if (i == 0 || board[i-1][j] == '.') {
leftMost = true;
}

bool topMost = false;
if (j == 0 || board[i][j-1] == '.') {
topMost = true;
}

return leftMost && topMost;

}

int countBattleships(vector<vector<char>>& board) {

int result = 0;

for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] == 'X' && isTopLeft(board, i, j)) {
result++;
}
}
}

return result;

}
``````