Leetcode题解:419. Battleships in a Board

Leetcode题解:419. Battleships in a Board

难度:Medium

题目

Given an 2D board, count how many different battleships are in it. The battleships are represented with ‘X’s, empty slots are represented with ‘.’s. You may ass
ume 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.

中文简述

在一个2d的棋盘上有各种形状不同的战船,船用’X’表示,空白处用’.’表示。船只有水平或者垂直两种方向,分别占1*n(n>=1)格。给定对应的棋盘,请你求出棋盘上有多少条战船。
ps:给定的棋盘都是有效棋盘,即两座船直接有间隔不会直接相连。
示例如下:

X..X
...X
...X

该图为有效棋盘,其中的船共2艘。

...X
XXXX
...X

该图为无效棋盘,其中两艘船有交叉无法分辨船体从属。

解题思路

解题思路多种多样,由于题目给出了有效和无效棋盘的定义,我们最暴力的方法就是通过遍历棋盘+DFS的方式,每遇到一个’X’就把这条船用深度优先搜索的方式把船体全部替换为’.’然后计数器+1,知道遍历完棋盘所有的节点。

第二种思路,是根据数船头数量来求得船的数量。不难发现根据给出的定义我们船头船尾元素有一下特点:上下左右四个方向中仅仅只有一个方向有’X’(超出棋盘的部分当做’.’处理),当我们选定船向右,向下延伸的时候时,船头元素就有如下性质:本位置为’X’,左方和上方为’.’或是越界。

源码

这里给出思路二的解法。

class Solution {
public:
     bool ishead(vector<vector<char>> &board, int i, int j){
        //cur_pos = 'X',up&left is .
        if(board[i][j]=='X'){
            if((i==0||board[i-1][j]=='.')&&(j==0||board[i][j-1]=='.'))
                return true;
        }
        return false;
    }

    int countBattleships(vector<vector<char>>& board) {
        if(board.empty())
            return 0;
        int rowsize = board.size();
        int colsize = board[0].size();
        int ans = 0;
        for (int i = 0; i < rowsize; ++i){
            for (int j = 0; j < colsize; ++j){
                if(ishead(board,i,j))
                    ans++;
            }
        }
        return ans;
    }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值