-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheight_puzzle_astar.cpp
99 lines (97 loc) · 2.54 KB
/
eight_puzzle_astar.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
95
96
97
98
99
#include<iostream>
#include<cstring>
#include<queue>
#include<map>
typedef std::pair<int,std::string> PIS;
std::string start = "";
std::string goal = "12345678x";
std::priority_queue<PIS,std::vector<PIS>,std::greater<PIS>> p;
std::map<std::string,std::string> m;
std::map<std::string, int> dis;
int dir[4][2] = {
{-1,0},{0,1},{1,0},{0,-1}
};
std::string op = "urdl";
int g(std::string s){
int ans = 0;
for(int i =0;i < 9;i++){
if(s[i]!='x'){
int y = s[i] - '1';
ans += abs(y/3-i/3) + abs(y%3-i%3);
}
}
return ans;
}
std::string astar(){
PIS st;
if(start==goal){
return "";
}
st.second = start;
st.first = g(st.second);
p.push(st);
m[start] = "";
dis[start] = 0;
while(!p.empty()){
PIS now = p.top();
p.pop();
int z;
std::string state = now.second;
for(int i = 0;i < 9;i++){
if(state[i]=='x'){
z = i;
break;
}
}
int x = z/3;
int y = z%3;
int distance = dis[state];
for(int i = 0;i < 4;i++){
int newx = x + dir[i][0];
int newy = y + dir[i][1];
int nz = newx*3+newy;
if(newx>=0&&newx<3&&newy>=0&&newy<3){
PIS newnode;
newnode.second = state;
std::swap(newnode.second[z],newnode.second[nz]);
newnode.first = distance + g(newnode.second) + 1;
if(dis.count(newnode.second)==0||dis[newnode.second] > dis[state] + 1){
m[newnode.second] = m[state] + op[i];
dis[newnode.second] = distance + 1;
p.push(newnode);
}
//std::cout << newnode.second <<std::endl;
//std::cout << m[newnode.second] <<std::endl;
if(newnode.second==goal){
return m[newnode.second];
}
}
}
}
return "unsolvable";
}
int main(){
char x;
std::string seq;
for(int i = 0;i < 9;i++){
std::cin >> x;
start += x;
if(x!='x'){
seq += x;
}
}
int cnt = 0;
for(int i = 0; i < 8; i++){
for(int j = i + 1; j < 8; j++){
if(seq[i] > seq[j]) cnt ++;
}
}
if(cnt & 1){
std::cout << "unsolvable";
}
else{
std::string ans = astar();
std::cout << ans;
}
return 0;
}