Skip to content

Commit ee2cdbd

Browse files
authored
[BOJ] 16928 뱀과 사다리 게임 (G5)
1 parent 90c8a44 commit ee2cdbd

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

박예진/10주차/260306.cpp

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
//https://www.acmicpc.net/problem/16928
2+
#include <iostream>
3+
#include <algorithm>
4+
#include <queue>
5+
#include <vector>
6+
7+
using namespace std;
8+
9+
/*
10+
사다리 타고 올라가기 (작 -> 큰)
11+
뱀 타고 내려가기 (큰 -> 작)
12+
*/
13+
14+
struct Node {
15+
int x, y;
16+
};
17+
18+
int N, M; // 사다리수, 뱀의수
19+
bool visited[101];
20+
vector<Node> ladders;
21+
vector<Node> snails;
22+
23+
int bfs(int x) {
24+
queue<pair<int, int>> q; // node, cnt
25+
q.push({x, 0});
26+
visited[x] = true;
27+
28+
while(!q.empty()) {
29+
pair<int, int> now = q.front();
30+
q.pop();
31+
32+
if (now.first == 100) {
33+
return now.second;
34+
}
35+
36+
for(int i = 1; i <= 6; i++){
37+
int next = now.first + i;
38+
39+
// 사다리 타기
40+
for(auto ladder : ladders) {
41+
if (ladder.x == next) {
42+
next = ladder.y;
43+
}
44+
}
45+
// 뱀 타기
46+
for(auto snail : snails) {
47+
if (snail.x == next) {
48+
next = snail.y;
49+
}
50+
}
51+
52+
if (next > 100) continue; // 범위 초과 시 스킵
53+
54+
if (!visited[next]) {
55+
visited[next] = true;
56+
q.push({next, now.second + 1});
57+
}
58+
}
59+
}
60+
return -1;
61+
}
62+
63+
int main(){
64+
ios_base::sync_with_stdio(false);
65+
cin.tie(NULL); cout.tie(NULL);
66+
67+
cin >> N >> M;
68+
// 사다리
69+
for(int i = 0; i < N; i++){
70+
int x, y;
71+
cin >> x >> y;
72+
ladders.push_back({x, y}); // x -> y
73+
}
74+
//
75+
for(int i = 0; i < M; i++){
76+
int u, v;
77+
cin >> u >> v;
78+
snails.push_back({u, v}); // u -> v
79+
}
80+
81+
cout << bfs(1);
82+
83+
84+
return 0;
85+
}

0 commit comments

Comments
 (0)