Battleships之间并不重叠这个assumption很关键,因此只要看船头就可以判断是不是有一个船
1 public class Solution { 2 public int countBattleships(char[][] board) { 3 int ans = 0; 4 for (int i = 0; i < board.length; i++) { 5 for (int j = 0; j < board[0].length; j++) { 6 if (board[i][j] == 'X' && ((i != 0 && board[i-1][j] != 'X') || i == 0) && ((j != 0 && board[i][j-1] !='X') || j == 0)) 7 ans++; 8 } 9 } 10 return ans; 11 } 12 }