LeetCode 419. Battleships in a Board (Medium)

来源:互联网 发布:阿里云服务器学生1元 编辑:程序博客网 时间:2024/06/08 19:29

题目描述:

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.

题目大意:给出一个图,竖着的X的组合或者横着的X的组合为一条船,船与船之间有空位(’.’),求船的数量。

思路:观察图可以发现,只要是一艘船,它的头的左边或者上边是不会有X的(因为它是头,如果左边有X说明它是横的船身,上边有X说明它是竖的船身)。那么只用遍历图,算出船头数量即可。
c++代码:

class Solution {public:    int countBattleships(vector<vector<char>>& board) {        int ans = 0;        for (int i = 0; i < board.size(); i++)        {            for (int j = 0; j < board[i].size(); j++)            {                if (board[i][j] == 'X')                {                    if (i == 0)                    {                        if (j == 0)                            ans++;                        else                        {                            if (board[i][j - 1] != 'X')                                ans++;                        }                    }                    else                    {                        if (j == 0)                        {                            if (board[i - 1][j] != 'X')                                ans++;                        }                        else                        {                            if (board[i - 1][j] != 'X' && board[i][j - 1] != 'X')                                ans++;                        }                    }                }               }        }        return ans;    }};
原创粉丝点击