1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
private int[][] directions = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };

public int countBattleships(char[][] board) {
int m = board.length, n = board[0].length;
boolean[][] visited = new boolean[m][n];
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'X' && !visited[i][j]) {
dfs(board, visited, i, j);
ans += 1;
}
}
}
return ans;
}

private void dfs(char[][] board, boolean[][] visited, int row, int col) {
visited[row][col] = true;
for (int[] direction : directions) {
int newRow = row + direction[0];
int newCol = col + direction[1];
if (!isOutOfBound(board, newRow, newCol) && board[newRow][newCol] == 'X' && !visited[newRow][newCol]) {
dfs(board, visited, newRow, newCol);
}
}
}

private boolean isOutOfBound(char[][] board, int row, int col) {
return row < 0 || row >= board.length || col < 0 || col >= board[0].length;
}
}

DFS就是.

时间复杂度: O(m * n) 遍历了整个board.
空间复杂度: O(m * n) 用了visited这个数组.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int countBattleships(char[][] board) {
int m = board.length, n = board[0].length, count = 0;
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (board[row][col] == '.')
continue;
if (row > 0 && board[row - 1][col] == 'X')
continue;
if (col > 0 && board[row][col - 1] == 'X')
continue;
count += 1;
}
}
return count;
}
}

这个做法十分聪明, 只是查每个battleship第一个cell. 我们定义第一个cell为top-left的那个.

时间复杂度和空间复杂度不变.