-
Notifications
You must be signed in to change notification settings - Fork 0
/
battleships.txt
43 lines (39 loc) · 1.25 KB
/
battleships.txt
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
40
41
42
43
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);
class Solution {
void dfs(vector<vector<char>>& board, int i, int j)
{
if (i<0 || i>=board.size() || j<0 || j>=board[0].size() )
return;
if (board[i][j]=='.')
return;
board[i][j]='.';
dfs(board, i-1, j);
dfs(board, i+1, j);
dfs(board, i, j-1);
dfs(board, i, j+1);
}
public:
int countBattleships(vector<vector<char>>& board)
{
if (board.size()==0)
return 0;
int count = 0;
for (int i=0; i<board.size(); i++)
{
for (int j=0; j<board[0].size();j++)
{
if(board[i][j]=='X')
{
count++;
dfs(board, i, j);
}
}
}
return count;
}
};