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:
1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.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?
1 public class Solution { 2 public int countBattleships(char[][] board) { 3 int m = board.length; 4 if (m == 0) return 0; 5 int n = board[0].length, count = 0; 6 7 for (int i = 0; i < m; i++) { 8 for (int j = 0; j < n; j++) { 9 if (board[i][j] == ‘.‘) continue; 10 if (i > 0 && board[i - 1][j] == ‘X‘) continue; 11 if (j > 0 && board[i][j - 1] == ‘X‘) continue; 12 count++; 13 } 14 } 15 return count; 16 } 17 }
原文:http://www.cnblogs.com/beiyeqingteng/p/6243618.html