그래프/BFS

뱀과 사다리 게임

4gats 2023. 5. 11. 14:50

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

 

16928번: 뱀과 사다리 게임

첫째 줄에 게임판에 있는 사다리의 수 N(1 ≤ N ≤ 15)과 뱀의 수 M(1 ≤ M ≤ 15)이 주어진다. 둘째 줄부터 N개의 줄에는 사다리의 정보를 의미하는 x, y (x < y)가 주어진다. x번 칸에 도착하면, y번 칸으

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
#include <iostream>
#include <algorithm>
#include <queue>
 
//next가 std에 이미 있으므로 next를 _next로 선언해준다
#define next _next
 
using namespace std;
int dist[101];
int next[101];
 
int main()
{
    int n, m;
    cin >> n >> m;
    
    for (int i = 1; i <= 100; i++)
    {
        next[i] = i;
        dist[i] = -1;
    }
    // 사다리
    while (n--)
    {
        int x, y;
        cin >> x >> y;
        next[x] = y;
    }
    //뱀
    while (m--)
    {
        int x, y;
        cin >> x >> y;
        next[x] = y;
    }
 
    dist[1= 0;
    queue<int> q;
    q.push(1);
 
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        for (int i = 1; i <= 6; i++)
        {
            int y = x + i;
            if (y > 100continue;
            y = next[y];
            if (dist[y] == -1)
            {
                dist[y] = dist[x] + 1;
                q.push(y);
            }
        }
    }
    cout << dist[100<< '\n';
    return 0;
}
cs