KDHzoot's Github

Code for study, project, etc

자세히보기

알고리즘/PS

[백준 7576] 토마토

kdhzoot 2018. 5. 18. 20:36

Union-find을 써서 시간을 줄이는 건줄 알았는데 그냥 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
#include <iostream>
#include <queue>
#define n_ 1005
using namespace std    ;
 
int n, m;
int arr[n_][n_];
int dx[4= { 0,1,0,-1 };
int dy[4= { 1,0,-1,0 };
 
typedef struct Point {
    int x, y, cnt;
}point;
 
queue <point> que;
 
void print() {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}
 
int check() {
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arr[i][j] == 0) {
                cnt++;
            }
        }
    }
    return cnt;
}
 
int bfs() {
    point now;
 
    while (!que.empty()) {
        now = que.front();
        que.pop();
 
        for (int i = 0; i < 4; i++) {
            int a = now.x + dx[i];
            int b = now.y + dy[i];
 
            if (a == -1 || a == n || b == -1 || b == m)continue;
            if (arr[a][b] == 0) {
                arr[a][b] = 1;
                que.push({ a, b, now.cnt + 1 });
            }
        }
    }
 
    int res = check();
    if (res != 0) {
        return -1;
    }
    return now.cnt;
}
 
int main(void) {
    cin >> m >> n;
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> arr[i][j];
            if (arr[i][j] == 1) {
                que.push({ i,j ,0 });
            }
        }
    }
 
    cout << bfs() << endl;
}
cs


'알고리즘 > PS' 카테고리의 다른 글

[백준 1202] 보석도둑  (0) 2018.05.18
[백준 13302] 리조트  (0) 2018.05.18
[백준 2448] 별찍기 - 11  (0) 2018.05.18
[백준 2447] 별찍기 - 10  (0) 2018.05.18
2의 n승 출력하기 (large)  (0) 2018.05.18