그래프/BFS

안전 영역

4gats 2023. 3. 14. 21:57

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

 

2468번: 안전 영역

재난방재청에서는 많은 비가 내리는 장마철에 대비해서 다음과 같은 일을 계획하고 있다. 먼저 어떤 지역의 높이 정보를 파악한다. 그 다음에 그 지역에 많은 비가 내렸을 때 물에 잠기지 않는

www.acmicpc.net

BFS 진행 순서가 정확해야 에러가 안뜬다!

ans의 최솟값은 1이다..

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
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <queue>
#include <cstring>
 
using namespace std;
 
int a[101][101];
int c_map[101][101];
bool check[101][101];
int n;
 
int dx[] = { 001-1 };
int dy[] = { 1-10,0 };
 
int x, y;
 
int main()
{
    cin >> n;
 
    int fall = 0;
 
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cin >> a[i][j];
            if (a[i][j] > fall)
                fall = a[i][j];
        }
    }
    
    // ans의 최솟값은 1
    int ans = 1;
 
    while (fall > 0)
    {
        memset(check, 0sizeof(check));
 
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                c_map[i][j] = a[i][j] - fall;
            }
        }
 
        int cnt = 0;
 
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                // bfs 시작 조건
                if (c_map[i][j] > 0 && check[i][j] == false)
                {
                    check[i][j] = true;
                    queue<pair<intint>> q;
                    q.push(make_pair(i, j));
 
                    while (!q.empty())
                    {
                        x = q.front().first;
                        y = q.front().second;
                        q.pop();
                        for (int k = 0; k < 4; k++)
                        {
                            int nx = x + dx[k];
                            int ny = y + dy[k];
                            if (0 <= nx && nx < n && 0 <= ny && ny < n)
                            {
                                if (c_map[nx][ny] > 0 && check[nx][ny] == false)
                                {
                                    check[nx][ny] = true;
                                    q.push(make_pair(nx, ny));
                                }
                            }
                        }
                    }
                    cnt++;
                }
            }
        }
 
        if (cnt > ans)
            ans = cnt;
 
        fall--;
    }
 
    cout << ans << '\n';
}
 
cs