zoukankan      html  css  js  c++  java
  • BFS解决九宫重排问题

    问题 1426: [蓝桥杯][历届试题]九宫重排

    时间限制: 1Sec 内存限制: 128MB 提交: 215 解决: 47

    题目描述

    如下面第一个图的九宫格中,放着  1~8  的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。经过若干次移动,可以形成第二个图所示的局面。

    我们把第一个图的局面记为:12345678. 
    把第二个图的局面记为:123.46758 
    显然是按从上到下,从左到右的顺序记录数字,空格记为句点。 
    本题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出-1。
    输入
    输入第一行包含九宫的初态,第二行包含九宫的终态。 
    输出
    输出最少的步数,如果不存在方案,则输出-1。
    样例输入
    12345678. 
    123.46758 
    样例输出
    3


    实现代码如下:
    (我用了string来记录已经出现过的排列情况,应该用其它方法储存速度会更快)

    #include<string.h>
    #include<iostream>
    #include<set>
    using namespace std;
    int main()
    {
    set<string>s;
    string arr[200000];
    int front=0;int rear=0;
    int dis[200000]={0};
    int pos=0;
    string beg,des;
    cin>>beg>>des;
    if(beg==des){cout<<0<<endl;return 0;
    }
    s.insert(beg);int dalta[4]={-1,1,-3,3};
    arr[front]=beg;
    while(front<=rear)
    {
    beg=arr[front];
    for(pos=0;pos<9;pos++)if(beg[pos]=='.')break;
    for(int i=0;i<4;i++)
    {
    if(pos==0||pos==1||pos==2)if(i==2)continue;
    if(pos==6||pos==7||pos==8)if(i==3)continue;
    if(pos==0||pos==3||pos==6)if(i==0)continue;
    if(pos==2||pos==5||pos==8)if(i==1)continue;
    int p=pos+dalta[i];
    char c=beg[pos];beg[pos]=beg[p];beg[p]=c;
    if(s.count(beg)==0)
    {
    s.insert(beg);
    arr[++rear]=beg;dis[rear]=dis[front]+1;
    if(beg==des)
    {
    cout<<dis[front]+1<<endl;return 0;
    }
    }
    c=beg[pos];beg[pos]=beg[p];beg[p]=c;
    }
    front++;
    }
    cout<<-1<<endl;return 0;
    }



  • 相关阅读:
    Hadoop2.5.2 安装部署
    Hadoop1.0.3安装部署
    水滴石穿
    使用tfrecord建立自己的数据集
    tesonflow实现word2Vec
    python+opencv 图像预处理
    ubuntu14.0 更改默认python为3.5 并安装tensorflow(cpu)
    python3.5+win7 安装 numpy 和scipy的总结
    关于matlab GUI 的一些总结
    23333 又是一篇水文章(以下是各种复制来的关于maven转成eclipse项目)
  • 原文地址:https://www.cnblogs.com/linruier/p/9485213.html
Copyright © 2011-2022 走看看