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; } }
|