1426: [蓝桥杯][历届试题] 九宫重排(双端bfs)

31 篇文章 0 订阅

题目

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

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

思路:
本题直接在棋盘上动手不是很好,要将每个棋盘的状态用矩阵压缩变成字符串进行bfs比较好,使用map方便进行判断是否走到过这种局势,queue更是bfs不能缺少的。

#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
string first, last, str1, str2;        //这里选择string类作为输出
int flag, x, y;
map<string, int>dis, vis;    //用map去重同时方便查询,dis表示开始找的点到当前点的距离
queue<string>q1, q2;        //两个队列
char m[3][3];                //九宫字符数组
const int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool in(int x, int y){                //判断是否超出九宫
    return x >= 0 && x < 3 && y >= 0 && y < 3;
}
void toMatrix(string str){                //把字符串变成九宫字符数组
    for(int i = 0; i < str.size(); i++){    //算法实现比较简单,模拟一下即可
        m[i / 3][i % 3] = str[i];
    }
}
string toString(){                    //把九宫字符数组转化为字符串
    string str;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            str.push_back(m[i][j]);        //一个一个push_back
        }
    }
    return str;
}
int dbfs(){                    //重头戏来了
    q1.push(first);            //q1从起点开始找
    dis[first] = 1;            //一开始赋值1
    vis[first] = 1;            //q1访问过的赋值为1
    q2.push(last);            //q2从终点开始找
    dis[last] = 1;
    vis[last] = 2;            //q2访问过的赋值为2
    while(!q1.empty() && !q2.empty()){//如果其中一个队列为空,还没有找到解,说明无解
        if(q1.size() < q2.size()){    //根据队列的容量来判断是从哪一端找,谁少谁出列
            str1 = q1.front();
            q1.pop();
            flag = 1;                //作一下是哪一个队列出列的标记
        }
        else{
            str1 = q2.front();
            q2.pop();
            flag = 2;
        }
        toMatrix(str1);                //转化为九宫数组
        for(int i = 0; i < 3; i++){        //找小数点
            for(int j = 0; j < 3; j++){
                if(m[i][j] == '.'){
                    x = i;
                    y = j;
                }
            }
        }
        for(int i = 0; i < 4; i++){        //四个方向开始试探
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(in(tx, ty)){
                swap(m[x][y], m[tx][ty]);        //试探
                str2 = toString(); 
                if(!dis.count(str2)){            //如果没有访问,就一下标记
                    dis[str2] = dis[str1] + 1;
                    vis[str2] = vis[str1];        //这样写可以避免判断是哪一端找的str2
                    if(flag == 1){                //谁出的列谁就入队
                        q1.push(str2);
                    }else if(flag == 2){
                        q2.push(str2);
                    }
                }
                else{            //如果已经访问判断标记是否重合
                    if(vis[str1] + vis[str2] == 3){
                        int ans = dis[str1] + dis[str2] - 1;//这里记得减一
                        return ans;
                    }
                }
                swap(m[x][y], m[tx][ty]);        //试探完毕一定要记得要回溯
            }
        }
    }
    return -1;                    //没有找到,返回-1
}
int main(){
    cin >> first >> last;
    if(first == last){
        cout << 0 << endl;
    }
    else{
        cout << dbfs() << endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C++实现广度优先算法实现九宫重排的示例代码: ```cpp #include <iostream> #include <queue> #include <vector> #include <map> using namespace std; // 目标状态 const vector<int> targetState = {1, 2, 3, 4, 5, 6, 7, 8, 0}; // 表示状态的结构体 struct State { vector<int> nums; // 状态数组 int zeroIndex; // 0的位置 int step; // 步数 State() {} State(vector<int> nums, int zeroIndex, int step) : nums(nums), zeroIndex(zeroIndex), step(step) {} }; // 广度优先搜索 int bfs(vector<int> startState) { queue<State> q; // 队列 map<vector<int>, bool> visited; // 记录已访问过的状态 State initState(startState, 0, 0); // 初始状态 q.push(initState); visited[startState] = true; while (!q.empty()) { State curState = q.front(); q.pop(); if (curState.nums == targetState) { // 已找到目标状态 return curState.step; } // 上下左右四个方向 int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; for (int i = 0; i < 4; i++) { int x = curState.zeroIndex / 3 + dx[i]; int y = curState.zeroIndex % 3 + dy[i]; if (x >= 0 && x < 3 && y >= 0 && y < 3) { // 位置合法 vector<int> newNums = curState.nums; swap(newNums[curState.zeroIndex], newNums[x * 3 + y]); if (!visited[newNums]) { // 新状态未曾访问过 State newState(newNums, x * 3 + y, curState.step + 1); q.push(newState); visited[newNums] = true; } } } } return -1; // 无法到达目标状态 } int main() { vector<int> startState = {2, 8, 3, 1, 6, 4, 7, 0, 5}; int step = bfs(startState); cout << step << endl; // 输出步数 return 0; } ``` 其,`State`结构体表示一个状态,包括`nums`表示状态数组,`zeroIndex`表示0的位置,`step`表示从初始状态到达该状态的步数。`bfs`函数实现广度优先搜索,`startState`为初始状态数组,返回从初始状态到目标状态需要的步数。在搜索过程,使用队列`q`存储待搜索的状态,使用`visited`记录已访问过的状态,遇到新状态时将其加入队列并标记为已访问。每次从队列取出一个状态,遍历其上下左右四个方向,生成新状态,并判断该状态是否已访问过,若未访问过则将其加入队列。最终,若搜索完所有状态仍未找到目标状态,则返回-1表示无法到达目标状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值