C++ 算法提高 八数码

算法提高 八数码

资源限制

时间限制:1.0s 内存限制:256.0MB

问题描述

RXY八数码

输入格式

输入两个3*3表格
  第一个为目标表格
  第二个为检索表格

输出格式

输出步数

样例输入

1 2 3
4 5 6
7 8 0
1 2 3
4 5 6
7 0 8

样例输出

1

数据规模和约定

332

代码

#include<string>
#include<map>
#include<iostream>
#include<queue>

using namespace std;

int change_x[4]={
     0,1,0,-1};
int change_y[4]={
     1,0,-1,0};

int main()
{
     
    string a,b,temp;
    for(int i=0;i<9;i++)
    {
     
        cin>>temp;
        a+=temp;
    }
    for(int i=0;i<9;i++)
    {
     
        cin>>temp;
        b+=temp;
    }
    map<string,int> m;
    m[a]=0;
    queue<string> q;
    q.push(a);
    int distance;
    while(q.size())
    {
     
        temp = q.front();
        q.pop();
        if(temp==b)
        {
     
            cout<<m[temp];
            return 0;
        }
        distance=m[temp];
        int index = temp.find('0');
        for(int i=0;i<4;i++)
        {
     
            int x=index/3+change_x[i];
            int y=index%3+change_y[i];
            if(x>2||x<0||y>2||y<0)
                continue;
            swap(temp[index],temp[x*3+y]);
            if(m.count(temp)==0)
            {
     
                m[temp]=distance+1;
                q.push(temp);
            }
            swap(temp[index],temp[x*3+y]);
        }
    }
}

你可能感兴趣的:(算法,c++)