蓝桥杯试题--九宫重排

题目概述

方法一 单向bfs

九宫重排问题就是典型的广度优先搜索问题,最初我的想法是利用单向的广度优先搜索实现,利用set来查重,通过广度优先搜索保证所需的步骤是最快的(关键点)。但是问题是单向的bfs速度上较慢,我在某些oj上运行不能通过,所以去查资料,发现还可以使用第二种方法。

方法二 双向bfs

单向虽然可以,但是速度比双向慢。因为随着递归的深度变深,每走一步要尝试更多种走法,双向bfs利用的就是两边同时走,在方向不同但是图案相同的点相遇。

借用别人的图来说明一下

 

代码如下

#include<iostream>
using namespace std;
#include<map>
#include<queue>

int dx[4] = { 0, 1, 0, -1 }, dy[4] = { -1, 0, 1, 0 };
string nextMat(string mat, int dir) {
    int dotInd = mat.find('.');
    int sucX = dotInd / 3 + dx[dir], sucY = dotInd % 3 + dy[dir];
    if (sucX < 0 || sucY < 0 || sucX>2 || sucY>2) return "null";
    swap(mat[dotInd], mat[(sucX * 3) + sucY]);
    return mat;
}

int bfs(string first, string endd)
{
    queue<string> Q;
    Q.push(first);
    Q.push(endd);
    map<string, int> thestep;
    map<string, int> thedirect;
    thestep[first] = 0; thestep[endd] = 0;
    thedirect[first] = 1; thedirect[endd] = 2;
    while (!Q.empty())
    {
        string str = Q.front();
        Q.pop();
        for (int i = 0; i < 4; i++)
        {
            string tempstr = nextMat(str, i);
            if (tempstr != "null" && thedirect[tempstr] != thedirect[str])
            {
                if (thedirect[tempstr] + thedirect[str] == 3)
                {
                    return thestep[tempstr] + thestep[str] + 1;
                }
                Q.push(tempstr);
                thedirect[tempstr] = thedirect[str];
                thestep[tempstr] = thestep[str] + 1;
            }

        }
    }
    return -1;
}

int main()
{
    string first, endd;
    cin >> first;
    cin >> endd;
    cout << bfs(first, endd);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值