티스토리 뷰

출저 : https://www.acmicpc.net/problem/10026


"BFS "


Red를 Green 으로 바꾸고 같은 색상 끼리 BFS를 돌려 구역을 구한다.


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.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
 
class Main {
    
    static int N;
    static char[][] map;
    static Queue<Point> q = new LinkedList<>();
    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 {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        N = Integer.parseInt(br.readLine());
        map = new char[N][N];
        visited = new boolean[N][N];
        
        for (int i = 0; i < N; i++) {
            char[] temp = br.readLine().toCharArray();
            for (int j = 0; j < N; j++) {
                map[i][j] = temp[j];
            }
        }
        
        int res1 = solve();
        
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if(map[i][j] == 'R')
                    map[i][j] = 'G';
            }
        }
        visited = new boolean[N][N];
        int res2 = solve();
        
        System.out.println(res1+" "+res2);
        
    }
    
    static int solve() {
        int cnt = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if(visited[i][j]) continue;
                
                visited[i][j] = true;
                q.add(new Point(i, j));
                
                while(!q.isEmpty()) {
                    
                    Point cur = q.poll();
                    
                    for (int k = 0; k < 4; k++) {
                        int nx = cur.x + dx[k];
                        int ny = cur.y + dy[k];
                        
                        if(!isRange(nx, ny) || visited[nx][ny] || map[nx][ny] != map[i][j]) {
                            continue;
                        }
                        
                        visited[nx][ny] = true;
                        q.add(new Point(nx, ny));
                        
                    }
                }
                cnt++;
            }
        }
        return cnt;
    }
    
    static boolean isRange(int x, int y) {
        if (x < 0 || x >= N || y < 0 || y >= N) return false;
        return true;
    }
}
cs



댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday