새발블로그
[백준/Java] 10026 적록색약 본문
문제
https://www.acmicpc.net/problem/10026
풀이방법
합쳐져있는 그래프 받기
일반사람이 보는 그래프랑 적록색약이 보는 그래프를 만듦
각각 BFS
풀이
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main{
public static void BFS(int N, char[][]map, boolean[][]visited, int[] cur) {
int[] dx = {0, -1, 0, 1};
int[] dy = {1, 0, -1, 0};
Queue<int[]> queue = new ArrayDeque<>();
queue.add(cur);
while (!queue.isEmpty()) {
int curX = queue.peek()[0];
int curY = queue.peek()[1];
visited[curX][curY] = true;
queue.poll();
for (int i = 0; i<4;i++) {
int nextX = curX + dx[i];
int nextY = curY + dy[i];
if (nextX>=0 && nextY >=0 && nextX<N && nextY <N) {
if (!visited[nextX][nextY] && map[nextX][nextY] == map[curX][curY]){
queue.add(new int[]{nextX, nextY});
visited[nextX][nextY] = true;
}
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
char[][] map1 = new char[N][N];
char[][] map2 = new char[N][N];
boolean[][] visited1 = new boolean[N][N];
boolean[][] visited2 = new boolean[N][N];
int cnt1 = 0;
int cnt2 = 0;
for (int i = 0 ;i<N; i++) {
String line = br.readLine();
map1[i] = line.toCharArray();
for (int j = 0; j<N; j++) {
//G를 R로
map2[i][j] = (line.charAt(j) == 'G') ? 'R' : line.charAt(j);
}
}
for (int i = 0; i<N; i++) {
for (int j = 0; j<N;j++) {
if (!visited1[i][j]) {
cnt1++;
BFS(N, map1, visited1, new int[]{i, j});
}
if (!visited2[i][j]) {
cnt2++;
BFS(N, map2, visited2, new int[]{i, j});
}
}
}
System.out.print(cnt1+" ");
System.out.print(cnt2);
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
| [백준/Java] 2579 계단 오르기 (0) | 2025.07.01 |
|---|---|
| [백준/Java] 21736 헌내기는 친구가 필요해 (0) | 2025.07.01 |
| [백준/Java] 1260 DFS와 BFS (0) | 2025.07.01 |
| [백준/Java] 2467 용액 (0) | 2025.07.01 |
| [백준/Java] 나무 자르기 (0) | 2025.07.01 |