首页 > 学院 > 开发设计 > 正文

419. Battleships in a Board

2019-11-08 01:24:31
字体:
来源:转载
供稿:网友

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?

class Solution {public: int countBattleships(vector<vector<char>>& board) { int row = board.size(); int col = board[0].size(); int cnt = 0; for(int i = 0; i < row; ++i){ for(int j = 0; j < col; ++j){ if(board[i][j] == 'X'){ if(i == 0){ if(j == 0 || board[i][j - 1] != 'X') ++cnt; } else { if(j == 0){ if(board[i - 1][j] != 'X') ++cnt; } else { if(board[i - 1][j] != 'X' && board[i][j - 1] != 'X') ++cnt; } } } } } return cnt; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表