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

来源:互联网 发布:js字符串截取方法 编辑:程序博客网 时间:2024/06/05 02:41
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) orNx1 (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 andwithout 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
原创粉丝点击