반응형

www.acmicpc.net/problem/13913

 

13913번: 숨바꼭질 4

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 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
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
// 10만보다 더 큰 곳으로 가서 -1 해서 갈 수도 있음
int n, k, now, visited[200001], parent[200001];
queue<int> q;
stack<int> s;
bool valid(int n) {
    if (!visited[n] && n >= 0 && n <= 100000)
        return true;
    return false;
}
void insert(int n) {
    if (valid(n)) {
        parent[n] = now;
        visited[n] = 1;
        q.push(n);
    }
}
void print() {
    while (now != -1) {
        s.push(now);        // 역순으로 출력하기 위해 stack 사용
        now = parent[now];    // 부모 따라서 계속 감
    }
    while (!s.empty()) {
        cout << s.top() << ' ';
        s.pop();
    }
}
 
void bfs(int start, int cnt) {
    parent[start] = -1;
    visited[start] = 1;
    q.push(start);
    while (!q.empty()) {
        cnt++;
        // 단계별로 진행
        int size = q.size();
        while (size--) {
            now = q.front();
            q.pop();
            
            if (now == k) {                // 동생 찾았으면 출력
                cout << cnt << '\n';
                print();
                exit(0);
            }
 
            insert(now - 1);            // Queue에 넣을 때 부모 정보 입력
            insert(now + 1);
            insert(now * 2);
        }
    }
}
int main() {
    cin >> n >> k;
    
    bfs(n, -1);
}
cs
반응형

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

백준 13549  (0) 2021.02.19
백준 14226 [복습 필수]  (0) 2021.02.19
백준 2178  (0) 2021.02.19
백준 1707  (0) 2021.02.19
백준 13023  (0) 2021.02.19

+ Recent posts