-
Notifications
You must be signed in to change notification settings - Fork 15
/
10503.cpp
65 lines (53 loc) · 1.45 KB
/
10503.cpp
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
62
63
64
65
/*
brute force > recursive backtracking
difficulty: medium
date: 14/Apr/2020
problem: given domino pieces, check if it is possible to arrive at a target piece from an initial piece using N intermediate pieces (possibly rotating them)
hint: DFS + backtracking
by: @brpapa
*/
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii; // node
const int UNVISITED = -1;
const int VISITED = 0;
int N;
map<pii, int> state;
pii target;
bool hasSolution;
void dfs(pii u, int lvl, bool rotate) {
// rotate: peça u foi colocada invertida?
if (hasSolution) return;
state[u] = VISITED;
if (u == target && !rotate && lvl == N+2) {
hasSolution = true;
return;
}
int last = rotate? u.first : u.second;
// para cada nó ligável à last
for (auto s : state) {
pii v = s.first;
if (state[v] == UNVISITED) {
if (last == v.first) dfs(v, lvl+1, 0);
if (last == v.second) dfs(v, lvl+1, 1);
}
}
state[u] = UNVISITED; // backtracking
}
int main() {
while (cin >> N && N) {
int M; cin >> M;
pii init; cin >> init.first >> init.second;
cin >> target.first >> target.second;
hasSolution = 0;
state.clear();
state[target] = UNVISITED;
while (M--) {
pii node; cin >> node.first >> node.second;
state[node] = UNVISITED;
}
dfs(init, 1, 0);
cout << (hasSolution? "YES":"NO") << endl;
}
return 0;
}