class Solution {
public int countBattleships(char[][] board) {
int res = 0, m = board.length, n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'X') {
res++;
helper(board, i, j);
}
}
}
return res;
}
public void helper(char[][] board, int i, int j) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != 'X')
return;
board[i][j] = '.';
helper(board, i, j - 1);
helper(board, i + 1, j);
helper(board, i, j + 1);
helper(board, i - 1, j);
}
}
요고
class Solution {
public int countBattleships(char[][] board) {
int r = board.length;
if(r == 0) return 0;
int c = board[0].length;
int count = 0;
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
if(board[i][j] == '.') continue;
if(i > 0 && board[i-1][j] == 'X') continue;
if(j > 0 && board[i][j-1] == 'X') continue;
count++;
}
}
return count;
}
}