- Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
- At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
So the problem becomes something similar to counting islands where islands here is 'X's surrounded by '.'.
1: class Solution {
2: public:
3: int countBattleships(vector<vector<char>>& board) {
4: int count = 0;
5: for (int i = 0; i < board.size(); i++) {
6: for (int j = 0; j < board[0].size(); j++) {
7: if (board[i][j] == 'X' && (i == 0 || board[i-1][j] != 'X') && (j == 0 || board[i][j-1] != 'X')) count++;
8: }
9: }
10: return count;
11: }
12: };