본문 바로가기

problem solving

7576번: 토마토

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
#include <iostream>
#include <queue>
#include <algorithm>
 
typedef struct {
    int y, x;
} dif;
 
dif dir[4= { {10}, {-10}, {01}, {0-1} };
 
int check[1001][1001= { 0 };
int map[1001][1001= { 0 };
 
int main(void) {
    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);
    
    int col, row;
    std::cin >> col >> row;
    std::queue<std::pair<dif, int>> mQ;
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            std::cin >> map[i][j];
            if (map[i][j] == 1) { 
                mQ.push({ {i, j}, 0 }); 
                check[i][j] = 1;
            }
        }
    }
 
    int count = 0;
    while (!mQ.empty()) {
        int y = mQ.front().first.y;
        int x = mQ.front().first.x;
        count = mQ.front().second;
        mQ.pop();
        for (int i = 0; i < 4; i++) {
            int tempY = y + dir[i].y;
            int tempX = x + dir[i].x;
            //std::cout << tempY << ", " << tempX << "\n";
            if (tempX < 0 || tempX >= col || tempY < 0 || tempY >= row) { continue; }
            if (check[tempY][tempX] || map[tempY][tempX] == -1continue;
            check[tempY][tempX] = 1;
            mQ.push({ {tempY, tempX}, count + 1 });
        }
    }
 
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            if (check[i][j] == 1 || map[i][j] == -1continue;
            std::cout << -1 << "\n";
            return 0;
        }
    }
 
    std::cout << count << "\n";
 
    return 0;
}
cs

'problem solving' 카테고리의 다른 글

9446번: 텀 프로젝트  (0) 2020.03.04
9019번: DSLR  (0) 2020.03.03
6588번: 골드바흐의 추측  (0) 2020.03.03
4949번: 균형잡힌 세상  (0) 2020.03.02
3108번: 로고  (0) 2020.03.02