반응형

www.acmicpc.net/problem/1697

 

1697번: 숨바꼭질

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

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
#include <iostream>
#include <queue>
#include <cstring>
#define rep(i,n) for(int i=0;i<n;i++)
#define pii pair<intint>
using namespace std;
int t, m, n, k, cnt;
int arr[51][51];
bool visited[51][51];
int dx[4= {10-10};
int dy[4= {010-1};
void bfs(int x, int y) {
    cnt++;
    queue<pii> q;
    q.push({ x, y });
    visited[x][y] = true;
    while (!q.empty()) {
        pii now = q.front();
        q.pop();
        int x = now.first;
        int y = now.second;
        rep(i, 4) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
                if (arr[nx][ny]==1 && !visited[nx][ny]) {
                    visited[nx][ny] = true;
                    q.push({ nx,ny });
                }
            }
        }
    }
 
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> t;
    while (t--) {
        cnt = 0;
        memset(arr, 0sizeof(arr));
        memset(visited, 0sizeof(visited));
        cin >> m >> n >> k;
        rep(i, k) {
            int a, b;
            cin >> a >> b;
            arr[b][a] = 1;
        }
 
        rep(i,n){
            rep(j, m) {
                if (arr[i][j] == 1 && !visited[i][j])
                    bfs(i, j);
            }
        }
        cout << cnt << '\n';
    }
}
 
 
 
cs
반응형

'백준 > DFS, BFS' 카테고리의 다른 글

백준 1707  (0) 2021.02.19
백준 13023  (0) 2021.02.19
백준 2583  (0) 2021.02.03
백준 2468  (0) 2021.02.03
백준 1012  (0) 2021.02.03

+ Recent posts