Given an 2D board, count how many battleships are in it. The battleships are represented with 'X'
s, empty slots are represented with '.'
s. You may assume the following rules:
- You receive a valid board, made of only battleships or empty slots.
- Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape
1xN
(1 row, N columns) orNx1
(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.
Example:
X..X ...X ...XIn the above board there are 2 battleships.
Invalid Example:
...X XXXX ...XThis is an invalid board that you will not receive - as battleships will always have a cell separating between them.
Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
class Solution {
public:
int x[4] = {0, 0, 1, -1};
int y[4] = {1, -1, 0, 0};
int countBattleships(vector<vector<char>>& board) {
int n = board.size();
int m = board[0].size();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'X') {
dfs(i, j, board);
count++;
}
}
}
return count;
}
void dfs(int i, int j, vector<vector<char>>& board) {
board[i][j] = '.';
for (int k = 0; k < 4; k++) {
int dx = i + x[k];
int dy = j + y[k];
if (dx >=0 && dx < board.size() && dy >= 0 && dy < board[0].size() && board[dx][dy] == 'X') dfs(dx, dy, board);
}
}
};
但是follow up要求只能用O(1)额外空间和遍历一次数组,以及不能改变board内的值,所以要考虑,因为这道题的题目里说只可能存在横着或者竖着的一排,不会有交叉,所以我们可以从上向下一排一排遍历,然后只计算第一个出现的X,这个时候就要分类讨论什么时候是第一个出现的,什么时候是和别的X连着的:
i= 0, j = 0时若为X肯定是第一个,因为是左上角第一个格子,count++
然后第一行向右遍历,i=0,j!=0时,只要左边一格为X就是连着的,左边一格为.就是第一个,count++
然后到第二行,考虑第一列的情况,i!=0, j=0时,只要上面一格为X就是连着的,上面一格为.就是第一个,count++
然后考虑i!=0,j!=0的情况,当左边一格和上面一格有一个为X就是连着的,都为.就是第一个,count++
代码如下:
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int n = board.size();
int m = board[0].size();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'X') {
if (i == 0 && j == 0) count++;
else if (i == 0 && j != 0) {
if (board[i][j-1] == '.') count++;
}
else if (i != 0 && j==0) {
if (board[i-1][j] == '.') count++;
}
else {
if (board[i-1][j] == '.' && board[i][j-1] == '.') count++;
}
}
}
}
return count;
}
};