数据弱,没加优化都过了。
dfs和bfs的题目我就不多说了,就是繁杂的模拟。
错了的话都是小问题。
#include<stdio.h>
#include<iostream>
#include<queue>
#include<algorithm>
#include<stdlib.h>
using namespace std;
const int max_n = 3628810;
const int max_r = 4;
bool f[max_n];
struct node
{
int m[4][4];
int x,y;
int c;
}now,next;
int ans[max_r][max_r];
queue <struct node> Q; //123804765
int re(struct node t)
{
int ans=0;
int i,j;
int u=1;
int v=2;
for (i=1;i<=3;i++)
for (j=1;j<=3;j++)
{
ans+=u*t.m[i][j];
u*=v;
v++;
}
return ans;
}
int init()
{
int i,j;
char c;
for (i=1;i<max_r;i++)
for (j=1;j<max_r;j++)
{
scanf("%c",&c);
ans[i][j]=c-'0';
}
now.m[1][1]=1;
now.m[1][2]=2;
now.m[1][3]=3;
now.m[2][1]=8;
now.m[2][2]=0;
now.m[2][3]=4;
now.m[3][1]=7;
now.m[3][2]=6;
now.m[3][3]=5;
now.x=2;
now.y=2;
now.c=0;
Q.push(now);
}
bool r(struct node t)
{
int i,j;
for (i=1;i<max_r;i++)
for (j=1;j<max_r;j++)
if (ans[i][j]!=t.m[i][j]) return false;
return true;
}
int work_put()
{
while (!Q.empty())
{
now=Q.front();
Q.pop();
if (r(now)) {printf("%d",now.c);return 0;}
int x,y;
x=now.x;
y=now.y;
if (x>1)
{
next=now;
next.c=now.c+1;
swap(next.m[x-1][y],next.m[x][y]);
next.x--;
if (!f[re(next)])
{
f[re(next)]=true;
Q.push(next);
}
}
if (x<3)
{
next=now;
next.c=now.c+1;
swap(next.m[x+1][y],next.m[x][y]);
next.x++;
if (!f[re(next)]){
f[re(next)]=true;
Q.push(next); }
}
if (y>1)
{
next=now;
next.c=now.c+1;
swap(next.m[x][y-1],next.m[x][y]);
next.y--;
if (!f[re(next)]){
f[re(next)]=true;
Q.push(next); }
}
if (y<3)
{
next=now;
next.c=now.c+1;
swap(next.m[x][y+1],next.m[x][y]);
next.y++;
if (!f[re(next)])
{
f[re(next)]=true;
Q.push(next);
}
}
}
}
int main()
{
init();
work_put();
return 0;
}