# 유형 : 탐색, 그래프

# 방법은 여러가지 있을텐데, 그냥 귀찮아서 입력받을때 적록색약인 사람을 위한 배열을 하나 더 만들었다.

그다음 BFS를 2번 돌리면 문제를 해결할 수 있다.

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
package bj;
 
import java.awt.Point;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
 
public class p10026 {
    static int N;
    static char arr[][], map[][];
    static boolean visit[][];
    static int moveX[] = {0,1,0,-1};
    static int moveY[] = {-1,0,1,0};
    static int cnt1,cnt2=0;
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        
        arr = new char[N][N];
        map = new char[N][N];
        visit = new boolean[N][N];
        
        for(int i=0; i<N; i++) {
            String str = br.readLine();
            for(int j=0; j<N; j++) {
                char ch = str.charAt(j);
                if(ch=='G') {
                    arr[i][j] = ch;
                    map[i][j] = 'R';
                }else {
                    arr[i][j] = ch;
                    map[i][j] = ch;
                }
            }
        }
        
        for(int i=0; i<N; i++) {
            for(int j=0; j<N; j++) {
                if(!visit[i][j]) {
                    bfs(i,j,arr);
                    cnt1++;
                }
            }
        }
        visit = new boolean[N][N];
        for(int i=0; i<N; i++) {
            for(int j=0; j<N; j++) {
                if(!visit[i][j]) {
                    bfs(i,j,map);
                    cnt2++;
                }
            }
        }
        System.out.println(cnt1+" "+cnt2);
    }
    
    public static void bfs(int i, int j, char ar[][]) {
        Queue<Point> queue = new LinkedList<Point>();
        char ch = ar[i][j];
        queue.add(new Point(j,i));
        visit[i][j] = true;
        while(!queue.isEmpty()) {
            Point p = queue.poll();
            int x = p.x;
            int y = p.y;
            
            for(int d=0; d<4; d++) {
                int newX = x + moveX[d];
                int newY = y + moveY[d];
                
                if(0<=newX && newX<&& 0<=newY && newY<&& !visit[newY][newX]) {
                    if(!visit[newY][newX] && ar[newY][newX]==ch) {
                        visit[newY][newX] = true;
                        queue.add(new Point(newX, newY));
                    }
                }
            }
        }
    }
}
 
cs

+ Recent posts