Post

[C++]๋ฐฑ์ค€ 11558๋ฒˆ The Game of Death

[C++]๋ฐฑ์ค€ 11558๋ฒˆ The Game of Death

๐Ÿ“Œ๋ฌธ์ œ ๋งํฌ


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

๐Ÿ“Œ๋ฌธ์ œ ์„ค๋ช…


๊ธฐ๋ณธ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ๋ฌธ์ œ์ด๋‹ค. 1๋ถ€ํ„ฐ ์ถœ๋ฐœํ•˜์—ฌ N์— ๋„์ฐฉํ•˜๋ฉด cnt๋ฅผ ์ถœ๋ ฅํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

๐Ÿ“Œ์ฝ”๋“œ


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 <algorithm>
#include <vector>
#include <queue>
using namespace std;
bool visited[10001];
vector<int> graph[10001];
int T, N, A;


void init(){
    for(int i = 1; i <= N; i++){
        visited[i] = false;
    }
    for(int i = 1; i <= N; i++){
        graph[i].clear();
    }
}

void bfs(){
    queue<pair<int, int>> q;
    q.push({1, 0});
    visited[1] = true;
    while(!q.empty()){
        auto [cur, cnt] = q.front();
        q.pop();
        if(cur == N){
            cout << cnt << '\n';
            return;
        }
        for(auto it : graph[cur]){
            if(!visited[it]){
                visited[it] = true;
                q.push({it, cnt + 1});
            }
        }
    }
    cout << 0 << '\n';
}

void input(){
    cin >> T;
    while(T--){
        cin >> N;
        init();
        for(int i = 1; i <= N; i++){
            cin >> A;
            graph[i].push_back(A);
        }
        bfs();
    }
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    input();
    return 0;
}
This post is licensed under CC BY 4.0 by the author.