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 34 35 36 37 38 39 40 41 42 43 44
| int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int r, c;
public void solve(char[][] board) { if (board == null || board.length == 0) return; this.r = board.length; this.c = board[0].length; for (int i = 0; i < r; i++) { if (board[i][0] == 'O') bfs(i, 0, board); if (board[i][c - 1] == 'O') bfs(i, c - 1, board); } for (int j = 0; j < c; j++) { if (board[0][j] == 'O') bfs(0, j, board); if (board[r - 1][j] == 'O') bfs(r - 1, j, board); } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { board[i][j] = board[i][j] == '*' ? 'O' : 'X'; } } }
private void bfs(int i, int j, char[][] board) { Queue<int[]> queue = new LinkedList<>(); queue.add(new int[]{i, j}); while (!queue.isEmpty()) { int size = queue.size(); for (int k = 0; k < size; k++) { int[] poll = queue.poll(); int x = poll[0]; int y = poll[1]; if (x >= 0 && x < r && y >= 0 && y < c && board[x][y] == 'O') { board[x][y] = '*'; for (int[] dir : dirs) { queue.offer(new int[]{x + dir[0], y + dir[1]}); } } } } }
|