LeetCode OJ-419.Battleships in a Board

LeetCode OJ-419.Battleships in a Board

题目描述

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:

...X
XXXX
...X

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

题目理解

​ ‘X’代表战舰,’.’代表分隔的空槽,战舰间必须有空槽分隔,才能多算一艘。战舰排列只会是横着的一行,或者竖着的一列,题目还明确表示给定数据一定合法。求战舰数量,只需判断该战舰位置的左边和上边是否为’.’即可。0行不需要判断上边,0列不需要判断左边。

Code

int count_battleships(const vector<vector<char>> &board)
{
    int count = 0;
    int i, j;
    if (board.size() == 0) {
        return count;
    }
    size_t row_cnt = board.size();
    size_t col_cnt = board[0].size();
    for (i = 0; i < row_cnt; ++i) {
        for (j = 0; j < col_cnt; ++j) {
            if (board[i][j] == 'X') {
                if (((i - 1 >= 0 && board[i - 1][j] == '.') || i - 1 < 0) &&
                    ((j - 1 >= 0 && board[i][j - 1] == '.') || j - 1 < 0))
                {
                    ++count;
                }
            }
        }
    }

    return count;
}

你可能感兴趣的:(OJ,ACM,leetcode,OJ)