洛谷 P1379 八数码难题

P1379 八数码难题

题目描述

在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字。棋盘中留有一个空格,空格用0来表示。空格周围的棋子可以移到空格中。要求解的问题是:给出一种初始布局(初始状态)和目标布局(为了使题目简单,设目标状态为123804765),找到一种最少步骤的移动方法,实现从初始布局到目标布局的转变。

输入输出格式

输入格式:

输入初试状态,一行九个数字,空格用0表示

输出格式:

只有一行,该行只有一个数字,表示从初始状态到目标状态需要的最少移动次数(测试数据中无特殊无法到达目标状态数据)

输入输出样例

输入样例#1:
283104765
输出样例#1:
4
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<map>
 5 using namespace std;
 6 map <string,int>v;
 7 map <string,int>step;
 8 int a,b,t,head=0,tail=0;
 9 int bh[]={-3,-1,1,3},wz[100000],tou[100000];
10 string s,rs("123804765"),dl[100000],ns;
11 int main(){
12     cin>>s;
13     a=s.find('0');
14     wz[head]=a;tou[head]=1;dl[head++]=s;
15     wz[head]=4;tou[head]=2;dl[head++]=rs;
16     v[s]=1;
17     while(tail<=head){
18         a=wz[tail];
19         t=tou[tail];
20         s=dl[tail++];
21         b=step[s];
22         for(int i=0;i<4;i++){
23             ns=s;
24             if(i==0&&a>2){
25                 ns[a]=s[a+bh[i]];ns[a+bh[i]]=s[a];
26             }
27             if(i==1&&a!=0&&a!=3&&a!=6){
28                 ns[a]=s[a+bh[i]];ns[a+bh[i]]=s[a];
29             }
30             if(i==2&&a!=2&&a!=5&&a!=8){
31                 ns[a]=s[a+bh[i]];ns[a+bh[i]]=s[a];
32             }
33             if(i==3&&a<6){
34                 ns[a]=s[a+bh[i]];ns[a+bh[i]]=s[a];
35             }
36             if(v[ns]!=t){
37                 if(!v[ns]){
38                     v[ns]=t;wz[head]=a+bh[i];tou[head]=t;
39                     dl[head++]=ns;step[ns]=b+1;
40                 }
41                 else{cout<<b+1+step[ns]<<endl;return 0;}    
42             }
43         }
44     }
45     return 0;
46 }

鞠爷的,原来就没搞懂,这辈也不想搞懂了

原文地址:https://www.cnblogs.com/suishiguang/p/6381275.html