
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static int size_x, size_y;
static char[][] normal_board;
static char[][] other_board;
static boolean[][] visited;
// 상 하 좌 우
static int[] dx = {0, 0, -1, 1};
static int[] dy = {-1, 1, 0, 0};
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
size_x = Integer.parseInt(br.readLine());
size_y = size_x;
normal_board = new char[size_y][size_x];
other_board = new char[size_y][size_x];
visited = new boolean[size_y][size_x];
for (int y = 0; y < size_y; y++) {
String temp = br.readLine();
for (int x = 0; x < size_x; x++) {
char ch = temp.charAt(x);
normal_board[y][x] = ch;
if (ch == 'R') {
ch = 'G';
}
other_board[y][x] = ch;
}
}
br.close();
//solve
int normal = 0;
int other = 0;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (isValidPos(y, x) && !visited[y][x]) {
bfs(y, x, normal_board);
normal++;
}
}
}
for (int i = 0; i < size_y; i++) {
Arrays.fill(visited[i], false); // clear
}
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (!visited[y][x]) {
bfs(y, x, other_board);
other++;
}
}
}
bw.write(normal + " " + other);
bw.close();
}
static void bfs(int y, int x, char[][] board) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{y, x});
char ch = board[y][x];
while (!queue.isEmpty()) {
int[] current = queue.poll();
int curY = current[0];
int curX = current[1];
for (int i = 0; i < 4; i++) {
int nextY = curY + dy[i];
int nextX = curX + dx[i];
if (isValidPos(nextY, nextX) && !visited[nextY][nextX] && board[nextY][nextX] == ch) {
queue.add(new int[]{nextY, nextX});
visited[nextY][nextX] = true;
}
}
}
}
static boolean isValidPos(int y, int x) {
return 0 <= y && y < size_y &&
0 <= x && x < size_x;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 16928번: 뱀과 사다리 게임 (0) | 2025.04.08 |
|---|---|
| [JAVA-자바] 7662번: 이중 우선순위 큐 (0) | 2025.04.07 |
| [JAVA-자바] 7569번: 토마토 (0) | 2025.04.04 |
| [JAVA-자바] 5430번: AC (0) | 2025.04.02 |
| [JAVA-자바] 5525번: IOIOI (0) | 2025.04.01 |