leetcode419. Battleships in a Board

53次阅读

共计 1183 个字符,预计需要花费 3 分钟才能阅读完成。

题目要求
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.
Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
假设有一个 2D 板,在板上用 X 表示战舰,已知板上任意两个战舰体之间一定会用. 隔开,因此不会出现两个 X 相邻的情况。现在要求用 O(N) 的时间复杂度和 O(1) 的空间复杂度来完成。
思路和代码
这题的思路非常清晰,我们只需要判断哪个 X 是战舰头即可,当我们遇到战舰头时,就将总战舰数加一,其余时候都继续遍历。战舰头即战舰的左侧和上侧没有其它的 X。
public int countBattleships(char[][] board) {
int count = 0;
if(board == null || board.length == 0 || board[0].length == 0) return count;
for(int i = 0 ; i<board.length ; i++) {
for(int j = 0 ; j<board[i].length ; j++) {
if(board[i][j] == ‘X’) {
if((i > 0 && board[i-1][j] == ‘X’) ||
(j > 0 && board[i][j-1] == ‘X’)) {
continue;
}
count++;
}
}
}
return count;
}

正文完
 0