题解——Leetcode 419. Battleships in a Board 难度:Medium

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 shape1xN (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.

Could you do it in one-pass, using onlyO(1) extra memory and without modifying the value of the board?


题目如上,简化后的题意如下:

给你一个方形的板,上面分布着战舰和狭槽,其中战舰用‘X’表示,狭槽用‘.’表示,但战舰的位置有一定限制。战舰可以是一行也可以是一列,而且战舰之间必须隔着狭槽。通过编程算出板上战舰的数量。

除此之外,题目还要求程序只能对板进行一次遍历,使用的额外内存的空间复杂度为O(1),并且不能修改板上战舰和狭槽的分布。


C++程序如下:

    class Solution {  
    public:  
        int countBattleships(vector<vector<char>>& board) {  
            int count=0;  
            for(int i = 0; i < board.size(); i++){  
                for(int j = 0; j < board[0].size(); j++)  
                    if(board[i][j]=='X'&&(i==0 || board[i-1][j]!='X')&&(j==0 || board[i][j-1] != 'X'))  
                        count++;  
            }  
            return count;  
        }  
    };  
战舰的数量等于战舰头的数量,所以当遍历board找到一个'X'时只需要判断它是不是战舰头即可。相对于战舰的非头位置,战舰横向排列时战舰头的左边必定为'.',纵向排列时上边必定为'.'。

函数countBattleships()的返回值为战舰的数量,函数参数为数据类型为二维容器的board,由于需要遍历board,所以设置两层嵌套的循环,外层循环次数为board.size()即板的行数,内层循环次数为board[0].size()即板的列数。在循环内判断遍历到的元素是否为战舰头,如果是就将战舰数量加1。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值