問題:數組
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:spa
1xN
(1 row, N columns) or Nx1
(N rows, 1 column), where N can be of any size.Example:code
X..X ...X ...X
In the above board there are 2 battleships.ip
Invalid Example:it
...X XXXX ...X
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.io
Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?ast
解決:class
① 求戰艦的個數,所謂的戰艦就是隻能是一行或者一列,不能有拐彎。本題限定了不會有相鄰的兩個戰艦的存在,有了這一點限制,那麼咱們只須要遍歷一次二維數組就好了,只要找出戰艦的起始點。所謂的戰艦起始點,就是指一條軍艦上最左邊的那個‘X’或者最上面的那個‘X’。遍歷
class Solution { //5ms
public int countBattleships(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) return 0;
int count = 0;
int m = board.length;
int n = board[0].length;
for (int i = 0;i < m;i ++){
for (int j = 0;j < n;j ++){
if (board[i][j] == '.' || (i > 0 && board[i - 1][j] == 'X') || (j > 0 && board[i][j - 1] == 'X')){
continue;
}
count ++;
}
}
return count;
}
}call
class Solution {//4ms public int countBattleships(char[][] board) { if(board.length == 0) return 0; int count = 0; for(int i = 0; i < board.length; i ++) { for(int j = 0; j < board[0].length; j ++) { if(board[i][j] == 'X') { if(i > 0 && board[i - 1][j] == 'X') continue; if(j > 0 && board[i][j - 1] == 'X') continue; count ++; } } } return count; } }