洛谷 P1379 八数码难题

题目描述

#include<complex>
#include<cstdio>
#include<algorithm>
using namespace std;
const int f[8][2]={{0,0},{0,1},{0,2},{1,2},{2,2},{2,1},{2,0},{1,0}};
//各个数字对应的目标位置 
const int dx[4]={0,1,-1,0},dy[4]={1,0,0,-1};
int sx,sy,deep;
char c[3][3];
inline int calc()
//计算现在数字的位置与目标位置的曼哈顿距离 
{
    int res=0;
    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            if(c[i][j]!='0')
                res+=abs(f[c[i][j]-'1'][0]-i)+abs(f[c[i][j]-'1'][1]-j);
    return res;
}
void dfs(int x,int y,int step,int pre)
{
    int tot=calc();
    if(!tot)
    {
        printf("%d
",step);
        exit(0);
    }
    if(tot+step>deep)return;
    for(int i=0;i<4;i++)
    {
        if(i+pre==3)continue;//若这一次方向与上一次方向相反则跳过 
        int xx=x+dx[i],yy=y+dy[i];
        if(xx>=0 && xx<3 && yy>=0 && yy<3)
        {
            swap(c[x][y],c[xx][yy]);
            dfs(xx,yy,step+1,i);
            swap(c[x][y],c[xx][yy]);
        }
    }
}
int main()
{
    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
        {
            scanf("%c",&c[i][j]);
            if(c[i][j]=='0')
                sx=i,sy=j;
        }
    while(1)
    {
        deep++;
        dfs(sx,sy,0,-1);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/LeTri/p/8688322.html