leetcode

来源:互联网 发布:网站的数据库是什么 编辑:程序博客网 时间:2024/06/11 22:36

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.

Example:

X..X...X...X
In the above board there are 2 battleships.

Invalid Example:

...XXXXX...X
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

Follow up:

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


mysolution:

大致思路:

题目大概意思是 隔列或者隔行排战舰,求这些战舰总数量。所以我们能准确找到每行或每列第一艘战舰即可。

class Solution {public:    int countBattleships(vector<vector<char>>& board) {        int num = 0;        if(board.size()==0)            return num;                int i = board.size();        int j = board[0].size();        for (int m = 0; m < i; ++ m)        {            for (int n = 0; n < j; ++n)            {                if(board[m][n] == '.') continue;                if(m > 0 && board[m -1][n] == 'X') continue;                if(n > 0 && board[m][n-1] == 'X') continue;                ++num;            }        }                return num;    }};


0 0