알고리즘/백준
[Java] 백준 10026 적록색약
24시간이모자란
2023. 5. 12. 03:29
문제
https://www.acmicpc.net/problem/10026
10026번: 적록색약
적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(초록)
www.acmicpc.net
특별한 조건 없는 일반적인 2차원 배열 탐색 문제
풀이
풀이 알고리즘은 다음과 같다.
- 적록색약이 있으면 if문으로 1 또는 2 에 해당하는지 검사하면서 dfs한다.
- 색약이 없는 경우 dfs 하면서 메소드 부른 횟수를 카운팅 한다.
- 정답을 리턴한다.
코드
package solve;
import java.io.*;
import java.util.*;
public class Main {
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solution();
}
public void solution() throws IOException {
FastReader fr = new FastReader();
int n = fr.nextInt();
int map[][] = new int[n][n];
String str ;
int k=0;
char c;
for(int i=0 ;i < n; i++){
str = fr.nextLine();
for(int j = 0 ;j < n; j++){
c = str.charAt(j);
switch (c){
case 'R':
k =0;
break;
case 'G':
k = 1;
break;
case 'B':
k =2 ;
break;
}
map[i][j] = k;
}
}
int a = getN(map, false);
int b = getN(map, true);
System.out.println(a + " " + b);
}
public int getN(int[][] m, boolean flag){
int n = m.length;
boolean v[][] = new boolean[n][n];
int ret =0;
for(int i =0 ;i <n ;i++){
for(int j = 0 ;j < n ;j++){
if(!v[i][j]){
v[i][j] = true;
dfs(m, v, i, j, flag, m[i][j]);
ret++;
}
}
}
return ret;
}
public void dfs(int[][] m, boolean[][] v, int x, int y, boolean f, int type){
for(int k =0 ;k <4; k++){
int nx = x + dx[k];
int ny = y + dy[k];
if(nx < 0 || ny < 0 || nx > m.length-1 || ny > m.length-1 || v[nx][ny] )continue;
if(f && (type ==1 || type ==0)){
if(m[nx][ny] ==2 )continue;
} else if (m[nx][ny] != type) {
continue;
}
v[nx][ny] = true;
dfs(m, v, nx, ny, f, type);
}
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}