-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path10422 - Knights in FEN.cpp
95 lines (77 loc) · 1.65 KB
/
10422 - Knights in FEN.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <set>
using namespace std;
int dx[] = { 2, -2, 1, -1, 2, -2, 1, -1 };
int dy[] = { 1, -1, 2, -2, -1, 1, -2, 2 };
vector<string> g;
queue<vector<string> > qu;
set<vector<string> > st;
bool check(vector<string> &fr) {
return fr[0] == "11111" &&
fr[1] == "01111" &&
fr[2] == "00 11" &&
fr[3] == "00001" &&
fr[4] == "00000";
}
pair<int, int> findSpace(vector<string> &fr) {
for(int i = 0; i < 5; ++i)
for(int j = 0; j < 5; ++j)
if(fr[i][j] == ' ')
return make_pair(i, j);
return make_pair(0, 0);
}
int BFS() {
while(!qu.empty()) qu.pop();
st.clear();
qu.push(g);
st.insert(g);
vector<string> fr;
pair<int, int> space;
int cost = 0, size;
while(!qu.empty()) {
size = qu.size();
while(size--) {
fr.clear();
fr = qu.front();
qu.pop();
if(check(fr))
return cost;
if(cost > 10)
return cost;
space = findSpace(fr);
for(int i = 0, nx, ny; i < 8; ++i) {
nx = space.first + dx[i];
ny = space.second + dy[i];
if(nx >= 0 && nx < 5 && ny >= 0 && ny < 5) {
swap(fr[space.first][space.second], fr[nx][ny]);
if(st.find(fr) == st.end()) {
qu.push(fr);
st.insert(fr);
}
swap(fr[space.first][space.second], fr[nx][ny]);
}
}
}
++cost;
}
return cost;
}
int main() {
int t;
cin >> t;
cin.ignore();
while(t-- != 0) {
g.clear();
g.resize(5);
for(int i = 0; i < 5; ++i)
getline(cin, g[i]);
int res = BFS();
if(res == 11) cout << "Unsolvable in less than 11 move(s)." << endl;
else cout << "Solvable in " << res << " move(s)." << endl;
}
return 0;
}