LeetCode[419] Battleships in a Board

来源:互联网 发布:海鸥手表怎么样 知乎 编辑:程序博客网 时间:2024/06/01 09:38

Given an 2D board, count how many different 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) 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.

Example:

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

Invalid Example:

...XXXXX...X
This is not a valid board - as battleships will always have a cell separating between them.

Your algorithm should not modify the value of the board.


遍历各点,遇到 'X' 就把cnt + 1,并且把经过的 ‘X’ 都变为 '.' 

class Solution {public:int countBattleships(vector<vector<char>>& board) {vector<vector<char>> tmp = board;int n1 = board.size(), n2 = board[0].size();int cnt = 0;for (int i = 0; i < n1; ++i) {for (int j = 0; j < n2; ++j) {if (tmp[i][j] == 'X') {tmp[i][j] = '.';++cnt;int a = i, b = j;while (a + 1 < n1 && tmp[a + 1][b] == 'X') {++a;tmp[a][b] = '.';}while (b + 1 < n2 && tmp[a][b + 1] == 'X') {++b;tmp[a][b] = '.';}}}}return cnt;}};

0 0
原创粉丝点击