rt,我感觉没啥问题,求助大佬们。
题目:


代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 4;
int sx, sy;
int g[N][N], wish[N][N] = {{0, 0, 1, 2}, {0, 3, 4, 5}, {0, 6, 7, 8}};
bool ju;
int depth;
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
bool ck()
{
for (int i = 1; i <= 3; i ++ )
for (int j = 1; j <= 3; j ++ )
if (g[i][j] != wish[i][j])
return 0;
return 1;
}
bool f(int rip)
{
int cnt = 0;
for (int i = 1; i <= 3; i ++ )
for (int j = 1; j <= 3; j ++ )
if (wish[i][j] != g[i][j])
{
cnt ++ ;
if (cnt + rip > depth) return 0;
}
return 1;
}
void dfs(int step, int x, int y, int pre)
{
if (step == depth)
{
if (ck()) {ju = 1;printf("%d\n", depth);exit(0);}
return;
}
if (ju) return;
for (int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if (a < 1 || b < 1 || a > 3 || b > 3 || pre + i == 3) continue;
swap(g[a][b], g[x][y]);
if (!ju && f(step)) dfs(step + 1, a, b, i);
swap(g[x][y], g[a][b]);
}
}
int main()
{
for (int i = 1; i <= 3; i ++ )
for (int j = 1; j <= 3; j ++ )
{
scanf("%d", &g[i][j]);
if (g[i][j] == 0) sx = i, sy = j;
}
if (ck()) {puts("0");return 0;}
while (!ju)
{
depth ++ ;
dfs(0, sx, sy, -1);
if (ju)
{
printf("%d\n", depth);
return 0;
}
}
return 0;
}