419 Battleships in a Board

Given a two-dimensional deck, count how many ships are in it. Battleships are represented by 'X' and vacancies are represented by '.'. You need to abide by the following rules:
    You are given a valid deck, consisting only of ships or vacancies.
    Ships can only be placed horizontally or vertically. In other words, a battleship can only be composed of 1xN (1 row, N columns), or Nx1 (N rows, 1 column), where N can be any size.
    There is at least one horizontal or vertical space separation between two ships - i.e. no adjacent ships.
Example:
X..X
...X
...X
has 2 ships in the deck above.
Invalid example:
...X
XXXX
...X
You will not receive invalid decks like this - because there will be at least one space between the ships to separate them.
Advanced:
Can you solve this problem with a one-scan algorithm, using only O(1) extra space, and without modifying the value of deck?
See: https://leetcode.com/problems/battleships-in-a-board/description/

C++:

class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {
        if (board.empty())
        {
            return 0;
        }
        int rsize = board.size();
        int csize = board[0].size();
        int count = 0;
        for (int i = 0; i < rsize; i++)
        {            
            for (int j = 0; j < csize; j++)
            {
                
                if (board[i][j] == 'X' && (i == 0 || board[i - 1][j] == '.') && (j == 0 || board[i][j - 1] == '.'))
                {
                    count++;
                }
            }
        }
        return count;
    }
};

 Reference: https://blog.csdn.net/camellhf/article/details/52871104

https://www.cnblogs.com/grandyang/p/5979207.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324521375&siteId=291194637