题目
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?
分析
给定一个2维板,计算其中包含多少艘不同的战舰。战舰用字符'X'表示,空白槽位用'.'表示。你应该假设如下规则:
- 给定的板子是有效的,只包含战舰和空白槽位。
- 战舰只能水平或者竖直放置。
- 战舰的尺寸可能不同。
- 两艘战舰之间在水平方向或者竖直方向至少包含一个空间—不会存在相邻的战舰。
因为战舰之间要用空白槽位隔开,因此遍历board,如果遇到一个战舰X,则看其左上是否有空白槽位,如果有,则是不同的战舰,令计数器加1,否则当前X只是左侧或者上侧战舰的一部分(即由多个X构成战舰),同理可以用右下等方向作为判定。
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int num=0;
if(board.size()==0||board[0].size()==0)
return 0;
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[i].size();j++)
num+=board[i][j]=='X'&&(i==0||board[i-1][j]=='.')&&(j==0||board[i][j-1]=='.');
}
return num;
}
};