반응형

문제출처

https://www.acmicpc.net/problem/7576


소스코드

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
#include <stdio.h>
#include <queue>
#define MAX 1000
using namespace std;
struct tomatoInfo {
    int cy, cx, time;
};
int n, m;
const int dx[] = {00-11};
const int dy[] = {1-100};
int map[MAX][MAX];
bool visit[MAX][MAX];
queue<tomatoInfo> q;
 
void init() {
    scanf("%d %d"&n, &m);
    for (int y=0; y<m; y++) {
        for (int x=0; x<n; x++) {
            scanf("%d"&map[y][x]);
            if (map[y][x] == 1) {
                q.push({y, x, 0});
                visit[y][x]=1;
            }
        }
    }
}
 
bool isOutOfBoundMap(int y, int x) {
    if (x<0 || y<0 || x>=|| y>=m) {
        return true;
    }
    return false;
}
 
bool checkMap() {
    for (int y=0; y<m; y++) {
        for (int x=0; x<n; x++) {
            if (map[y][x]==0) {
                return false;
            }
        }
    }
    return true;
}
 
void bfs() {
    int t;
    while (!q.empty()) {
        int y = q.front().cy;
        int x = q.front().cx;    
        t = q.front().time;
        q.pop();
        
        for (int i=0; i<4; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];
            
            if (isOutOfBoundMap(ny, nx) || visit[ny][nx]) {
                continue;
            }
            if (map[ny][nx] == 0 && !visit[ny][nx]) {
                q.push({ny, nx, t+1});
                map[ny][nx]=1;
                visit[ny][nx]=1;
            }
        }
    }
    
    checkMap()==1 ? printf("%d", t) : printf("-1");    
}
int main() {
    init();
    bfs();
    return 0;
}
cs


반응형

'Algorithm' 카테고리의 다른 글

[SWEA 2805] 농작물 수확하기  (0) 2019.07.23
[SWEA 5162] 두가지 빵의 딜레마  (0) 2019.07.23
[BOJ 1206] DFS와 BFS  (0) 2019.07.05
[BOJ 1120]문자열  (0) 2019.07.03
[BOJ 5585] 거스름돈  (0) 2019.07.03

+ Recent posts