[LeetCode] Battleships in a Board

419. Battleships in a Board

Given an m x n matrix board where each cell is a battleship ‘X’ or empty ‘.’, return the number of the battleships on board.

Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
bool isNearShip(vector<vector<char>>& board, int y, int x) {
if(y == -1 or y == board.size()) return false;
if(x == -1 or x == board[y].size()) return false;
return board[y][x] == 'X';
}

bool horizonShip(vector<vector<char>>& board, int y, int x) {
return !isNearShip(board, y + 1, x) and !isNearShip(board, y - 1, x);
}
public:
int countBattleships(vector<vector<char>>& board) {
int n = board.size(), m = board[0].size();
int res = 0;
for(int i = 0; i < m; i++) { //check vertical
for(int j = 0; j < n - 1; j++) {
if(board[j][i] == '.') continue;
if(board[j + 1][i] == '.') continue; //if no vertical, pass
int nextJ = j + 2;

while(nextJ < n and board[nextJ][i] == 'X') nextJ++;
j = nextJ;
res++;
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(board[i][j] == '.') continue;
if(!horizonShip(board,i,j)) continue;
int nextJ = j + 1;
while(nextJ < m and board[i][nextJ] == 'X') nextJ++;
j = nextJ;
res++;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/battleships-in-a-board/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.