419. Battleships in a Board

406 篇文章 0 订阅
406 篇文章 0 订阅

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值