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

来源:互联网 发布:ubuntu qemu kvm 编辑:程序博客网 时间:2024/06/14 14:14
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;    }};
函数countBattleships()的返回值为战舰的数量,函数参数为数据类型为二维容器的board,由于需要遍历board,所以设置两层嵌套的循环,外层循环次数为board.size()即板的行数,内层循环次数为board[0].size()即板的列数。

在循环内执行一个判断,由于战舰之间必须隔着狭槽,所以当战舰位于board的最左上角时,战舰的数量加1;当战舰位于第一行时,只要保证战舰左边不挨着另一条战舰即可;当战舰位于第一列时,只要保证战舰上面不挨着另一条战舰即可;当战舰不位于board的四边上,则需要保证战舰的上边和左边不挨着战舰。

根据以上规则,遍历一遍整个board,就可以数出所有符合规则的战舰。


0 0