Skip to content

Commit b81c75e

Browse files
authored
Create battleships-in-a-board.cpp
1 parent 7f9596b commit b81c75e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

C++/battleships-in-a-board.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(m * n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int countBattleships(vector<vector<char>>& board) {
7+
if (board.empty() || board[0].empty()) {
8+
return 0;
9+
}
10+
11+
int cnt = 0;
12+
for (int i = 0; i < board.size(); ++i) {
13+
for (int j = 0; j < board[0].size(); ++j) {
14+
cnt += board[i][j] == 'X' &&
15+
(i == 0 || board[i - 1][j] != 'X') &&
16+
(j == 0 || board[i][j - 1] != 'X');
17+
}
18+
}
19+
return cnt;
20+
}
21+
};

0 commit comments

Comments
 (0)