-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path100000609-02.cpp
90 lines (80 loc) · 1.93 KB
/
100000609-02.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
#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
const int offset[] = {-3, +3, -1, +1};
struct Node {
vector<int> matrix;
int step;
} start;
vector<int> target;
set<vector<int> > inq;
bool is_achieved(vector<int> &v)
{
for (int i = 0; i < 9; i++)
if (v[i] != target[i])
return false;
return true;
}
bool is_valid_offset(int pos, int offset)
{
int x = pos / 3, y = pos % 3,
offset_x = offset / 3, offset_y = offset % 3,
new_x = x + offset_x, new_y = y + offset_y;
return (0 <= new_x && new_x < 3) &&
(0 <= new_y && new_y < 3);
}
int bfs()
{
queue<Node> q;
q.push(start);
inq.insert(start.matrix);
while (!q.empty())
{
Node front = q.front();
q.pop();
if (is_achieved(front.matrix)) return front.step;
// find the blank space
int blank;
for (int i = 0; i < 9; i++)
if(front.matrix[i] == 0)
{
blank = i;
break;
}
// 岔路口
for (int i = 0; i < 4; i++)
if (is_valid_offset(blank, offset[i]))
{
swap(front.matrix[blank], front.matrix[blank + offset[i]]);
if (!inq.count(front.matrix))
{
inq.insert(front.matrix); // mark as in-queued
front.step++;
q.push(front);
front.step--; // recver;
}
swap(front.matrix[blank], front.matrix[blank + offset[i]]); // revcover
}
}
return 0;
}
int main()
{
int tmp;
for (int i = 0; i < 9; i++)
{
scanf("%d", &tmp);
start.matrix.push_back(tmp);
}
start.step = 1;
for (int i = 0; i < 9; i++)
{
scanf("%d", &tmp);
target.push_back(tmp);
}
printf("%d", bfs());
return 0;
}