LC.P419[甲板上的战舰]

方法一:遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int countBattleships(char[][] board) {
int m = board.length, n = board[0].length;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == 'X') {
board[i][j] = '.';
for (int k = j + 1; k < n && board[i][k] == 'X'; ++k) {
board[i][k] = '.';
}
for (int k = i + 1; k < m && board[k][j] == 'X'; ++k) {
board[k][j] = '.';
}
++ans;
}
}
}
return ans;
}
}
  • 时间复杂度:$O(m \times n \times max(m.n))$
  • 空间复杂度:$O(1)$

方法二:枚举左端点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int countBattleships(char[][] board) {
int m = board.length, n = board[0].length;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == 'X') {
if (i > 0 && board[i - 1][j] == 'X') continue;
if (j > 0 && board[i][j - 1] == 'X') continue;
++ans;
}
}
}
return ans;
}
}
  • 时间复杂度:$O(m \times n)$
  • 空间复杂度:$O(1)$