【宽搜】Vijos P1360 八数码问题

题目链接:

  https://vijos.org/p/1360

题目大意:

  3x3格子上放1~8数字,一个空位,每次空位可与上下左右交换,固定终止布局,求输入的起始布局需要几步到达终止布局

题目思路:

  【搜索】

  一眼题BFS,宽搜即可,判重我比较暴力直接把状态记下,没hash、cantor什么的。

 

 1 //
 2 //by coolxxx
 3 //
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<string>
 7 #include<iomanip>
 8 #include<memory.h>
 9 #include<time.h>
10 #include<stdio.h>
11 #include<stdlib.h>
12 #include<string.h>
13 #include<stdbool.h>
14 #include<math.h>
15 #define min(a,b) ((a)<(b)?(a):(b))
16 #define max(a,b) ((a)>(b)?(a):(b))
17 #define abs(a) ((a)>0?(a):(-(a)))
18 #define sqr(a) (a)*(a)
19 #define swap(a,b) (a)^=(b),(b)^=(a),(a)^=(b)
20 #define eps 1e-8
21 #define S 10000
22 #define MAX 0x7f7f7f7f
23 #define PI 3.1415926535897
24 #define N 14
25 #define M 100000
26 using namespace std;
27 int n,m,cas,lll,ans;
28 int r[N]={1,10,100,1000,10000,100000,1000000,10000000,100000000};
29 int d[4]={-3,-1,1,3};
30 int q[M][N]={1,2,3,8,0,4,7,6,5};
31 int v[M];
32 bool u[87654321];
33 bool ok(int x,int y)
34 {
35     if(y==-3)return (x/3>0);
36     if(y==-1)return (x%3>0);
37     if(y==1) return (x%3<2);
38     if(y==3) return (x/3<2);
39 }
40 int spfa()
41 {
42     int i,j,now,h=-1,t=0;
43     int x;
44     u[m%r[8]]=1;
45     while(h++<t)
46     {
47         for(x=0,i=0;i<9;i++)
48         {
49             x+=q[h][i]*r[8-i];
50             if(q[h][i]==0)now=i;
51         }
52         if(x==n)return v[h];
53         for(i=0;i<4;i++)
54         {
55             if(ok(now,d[i]))
56             {
57                 memcpy(q[t+1],q[h],sizeof(q[h]));
58                 swap(q[t+1][now],q[t+1][now+d[i]]);
59                 for(x=0,j=1;j<9;j++)
60                     x+=q[t+1][j]*r[8-j];
61                 if(!u[x])
62                 {
63                     v[++t]=v[h]+1;
64                     u[x]=1;
65                 }
66             }
67         }
68     }
69 }
70 int main()
71 {
72     #ifndef ONLINE_JUDGE
73     //freopen("1.txt","r",stdin);
74     //freopen("2.txt","w",stdout);
75     #endif
76     int i,j,k;
77     //while(~scanf("%s%s",sn,sm))
78     while(~scanf("%d",&n) && n)
79     {
80         m=123804765;
81         printf("%d\n",spfa());
82     }
83     return 0;
84 }
85 
86 
87 /*
88 //
89 
90 //
91 */
View Code

 

转载于:https://www.cnblogs.com/Coolxxx/p/5313872.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值