1,题目要求
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.
给定一个二维的战舰位置图,求出战舰的数量。
2,题目思路
对于这道题,首先题目所给定的战舰位置的二维图,全部都是满足条件的、合法的二维图,不是题目介绍中的那种不合法的图。
其次,对于一个战舰,如果它在图中,那么它所占有的一定是1*N或者N*1的大小的格子。其中这个N可以是任何数字(只要不超过整个网格的大小即可)。因此1*1也行,1*3也行,3*1也行。不过要求是两艘战舰不可以挨在一起,中间必须有“.”作为分隔。
因此,对于这道题,我们只需要对连续出现的横着的x和竖着的x进行判断即可。
3,程序源码
static int pr = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int m = board.size(), n = board[0].size(), res = 0;
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++)
{
if(board[i][j] == '.') continue;
if((i > 0 && board[i-1][j] == 'X') || (j > 0 && board[i][j-1] == 'X')) continue;
res++;
}
return res;
}
};