728x90
반응형
SMALL
해석 적기
import java.util.LinkedList;
import java.util.Queue;
class Solution {
static int[] dx = {1, 0, -1, 0};
static int[] dy = {0, 1, 0, -1};
public void solve(char[][] board) {
int rows = board.length, cols = board[0].length;
Queue<int[]> queue = new LinkedList<>();
// Step 1: 경계에 있는 'O'를 찾아 큐에 추가하고 'T'로 변경
for (int i = 0; i < rows; i++) {
if (board[i][0] == 'O') bfs(board, i, 0, queue);
if (board[i][cols - 1] == 'O') bfs(board, i, cols - 1, queue);
}
for (int j = 0; j < cols; j++) {
if (board[0][j] == 'O') bfs(board, 0, j, queue);
if (board[rows - 1][j] == 'O') bfs(board, rows - 1, j, queue);
}
// Step 2: 보드를 순회하며 'O'를 'X'로 변경, 'T'를 'O'로 복구
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'O') board[i][j] = 'X';
if (board[i][j] == 'T') board[i][j] = 'O';
}
}
}
private void bfs(char[][] board, int x, int y, Queue<int[]> queue) {
queue.add(new int[]{x, y});
board[x][y] = 'T';
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int k = 0; k < 4; k++) {
int nx = cur[0] + dx[k];
int ny = cur[1] + dy[k];
if (nx >= 0 && ny >= 0 && nx < board.length && ny < board[0].length && board[nx][ny] == 'O') {
board[nx][ny] = 'T'; // 경계와 연결된 'O'는 'T'로 변경
queue.add(new int[]{nx, ny});
}
}
}
}
}
728x90
반응형
SMALL
'문제 풀이' 카테고리의 다른 글
[java] 소수 구하기 - 에라토스테네스의 체 (3) | 2023.12.17 |
---|