Completion over Perfection

백준 10026 - 적록색약 (JAVA 자바) 본문

앨고리듬 알고리즘

백준 10026 - 적록색약 (JAVA 자바)

난차차 2021. 1. 28. 21:20
반응형

백준 10026 - 적록색약 (JAVA 자바)

 

비교적 쉬운편에 속하는 DFS 문제입니다. 

쉬운만큼 기초다지기에 좋은 문제입니다. 

 

 

 

저는 아래와 같이 풀었습니다. 참고해주세요~

 

1. 데이터입력받을 때 1줄씩 받고, charAt 을 통해 한글자씩 잘라서 map[][] 배열에 저장해준다.

2. 색약이 아닌 사람의 경우와 색약인 사람의 경우를 나눠서 2번 DFS를 돌려준다. 

3. 색약인 사람의 경우에는 녹색과 적색을 구분 못하므로, G를 R로 모두 바꿔준 후에 DFS를 돌렸다.

4. visits[][] 배열은 두번째 돌리기 전에 초기화를 시켜줘야 된다. 

 

 

 

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.*;
 
public class daltonism {
 
    static int n;
    static String s;
    static char map[][];
    static boolean visits[][];
    static int dx[] = {-1,0,0,1};
    static int dy[] = {0,1,-1,0};
 
    public static void main(String args[]) {
 
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        map = new char[n+1][n+1];
        visits = new boolean[n+1][n+1];
 
        for (int i=0; i<n; i++){
            s = sc.next(); // RRRBB
            for (int j=0; j<n; j++){
                map[i][j] = s.charAt(j); // R R R B B
            }
        }
 
        // normal 인 경우
        int cnt = 0;
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                if(!visits[i][j]){
                    dfs(i,j);
                    cnt++;
                }
            }
        }
        int normal_cnt = cnt;
        cnt=0;
        visits = new boolean[n+1][n+1];
 
        // dltonism 인 경우
        // G를 R로 바꿔주고 돌린다.
 
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                if(map[i][j]=='G'){
                    map[i][j] = 'R'// G를 R로 바꿔준다.
                }
            }
        }
        //
 
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                if(!visits[i][j]){
                    dfs(i,j);
                    cnt++;
                }
            }
        }
        int abnormal_cnt = cnt;
        System.out.println(normal_cnt + " " + abnormal_cnt);
 
    }
 
    public static void dfs(int x, int y){
        visits[x][y] = true;
        char tmp_char = map[x][y]; // R
        for(int i=0; i<4; i++){
            int new_x = x+dx[i];
            int new_y = y+dy[i];
 
            if (new_x<0 || new_y<0 || new_x>|| new_y>n){
                continue;
            }
 
            if (!visits[new_x][new_y] && map[new_x][new_y] == tmp_char){
                dfs(new_x, new_y);
            }
        }
    }
    
}
cs
반응형
Comments