Luogu P1379 八数码难题

普通广搜

  • 广搜,移动0的位置,并且用map去重,顺便map也记录一下最小步数。
  • 采用long long保存一下状态,逐层深入,直到找到答案。
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
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

int xc[4] = {1, -1, 0, 0};
int yc[4] = {0, 0, -1, 1};

struct Solution{
ll begin;
map<ll, int> hash;

void Solve(){
scanf("%lld", &begin);
queue<ll> q;
q.push(begin);
while(!q.empty()){
int state = q.front();
q.pop();
if(state == 123804765) break;
int a[3][3], x, y;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
a[i][j] = (int)(state / (pow(10, 9 - (i * 3 + j + 1)))) % 10;
if(!a[i][j]) x = i, y = j;
}
}//long long转矩阵
for(int i = 0; i < 4; i++){
int xn = x + xc[i], yn = y + yc[i];
if(xn > 2 || xn < 0 || yn > 2 || yn < 0) continue;
swap(a[xn][yn], a[x][y]);
ll now = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
now = now * 10 + a[i][j];
}
}//矩阵转long long
if(hash[now] == 0){
//如果没有保存过就压入队列
hash[now] = hash[state] + 1;
q.push(now);
}
swap(a[xn][yn], a[x][y]);
}
}
printf("%d", hash[123804765]);
}
};

int main(){
Solution().Solve();
return 0;
}
# 搜索

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×