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) 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 ...XIn the above board there are 2 battleships.
Invalid Example:
...X XXXX ...XThis 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?
平板上的战船。题意是给一个二维数组,包括了点和X。判断有几个战舰。战舰的定义是必须是横的或者直的并且任意两个战舰之间至少有一个cell的间隔。
这个题的followup是问是否只扫描一遍并且不用额外空间。思路是遍历一次input,找出战舰的起始点。所谓的战舰起始点,就是为X的点,而且该点的上方和左边的点不能为X。这题其实是比较简单,因为如果战舰可以相邻,会更难判断。
二刷的时候这道题看了答案都不记得为什么上方和左边的点不能为X,原因是因为每个单独的战舰是不能跟其他战舰相邻的,我们既然找的是战舰的起点,中间一定要隔开起码一个坐标的距离。
时间O(n^2)
空间O(1)
JavaScript实现
1 /** 2 * @param {character[][]} board 3 * @return {number} 4 */ 5 var countBattleships = function(board) { 6 let m = board.length; 7 if (m === 0) return 0; 8 let n = board[0].length; 9 let res = 0; 10 for (let i = 0; i < m; i++) { 11 for (let j = 0; j < n; j++) { 12 if (board[i][j] === '.') continue; 13 if (i > 0 && board[i - 1][j] === 'X') continue; 14 if (j > 0 && board[i][j - 1] === 'X') continue; 15 res++; 16 } 17 } 18 return res; 19 };
Java实现
1 class Solution { 2 public int countBattleships(char[][] board) { 3 int m = board.length; 4 if (m == 0) { 5 return 0; 6 } 7 int n = board[0].length; 8 int res = 0; 9 for (int i = 0; i < m; i++) { 10 for (int j = 0; j < n; j++) { 11 if (board[i][j] == '.') 12 continue; 13 if (i > 0 && board[i - 1][j] == 'X') 14 continue; 15 if (j > 0 && board[i][j - 1] == 'X') 16 continue; 17 res++; 18 } 19 } 20 return res; 21 } 22 }