419. Battleships in a Board
X..X
...X
...X...X
XXXX
...Xint countBattleships(vector<vector<char>>& board) { // time: O(m * n); space: O(1)
int m = board.size(), n = board[0].size(), res = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == '.' ||
(i > 0 && board[i - 1][j] == 'X') ||
(j > 0 && board[i][j - 1] == 'X')) continue;
++res;
}
}
return res;
}Last updated