题目
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) or Nx1 (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
…X
In the above board there are 2 battleships.
Invalid Example:(反例)
…X
XXXX
…X
This 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 countBattleships(vector<vector<char>>& board) {
}
};
简单翻译理解:
给一个二维平面,数出其中战船的个数。战船用数个X代替,空着的槽位用.表示,你应该遵守(假设?)已下规则:
1. 你接收到有效的平面,只有战船和空槽组成。
2. 战舰只能水平或者竖直放置,或者说,他们只能是1*N或N*1,N可以是各种尺寸。
3. 两艘战舰之间在水平方向或者竖直方向至少包含一个空间,不存在相邻紧贴的战舰。
一次遍历,只使用O(1)额外的内存,而不修改board的值?(黑人问号??)
int countBattleships(vector<vector<char>>& board) {
int h = board.size();
if (!h) return 0;
int w = board[0].size();
if (!w) return 0;
int cnt = 0;
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
{
if (board[i][j] == 'X')
{
if (!(i > 0 && board[i - 1][j] == 'X'))
//检查上一行是否是‘X’
{
//如不是,计数+1.
cnt++;
while (j < (w - 1) && board[i][j + 1] == 'X')
j++;
//还没有到最底层时,看这个位置右边是否是‘X’,如果是,位置向右挪。
}
}
}
return cnt;
}
总结:
开始的时候,一直没有写:
if (!h) return 0;
if (!w) return 0;
这个是参考别人的,大家有很多种写法,还有网上有很多种我不知道的获取band长宽的方法,以后我会补充进这个博客。