bfs之八数码

19 篇文章 0 订阅
18 篇文章 0 订阅

在一个 3×3 的网格中,1∼8 这 8 个数字和一个 x 恰好不重不漏地分布在这 3×3 的网格中。

例如:

1 2 3
x 4 6
7 5 8
在游戏过程中,可以把 x 与其上、下、左、右四个方向之一的数字交换(如果存在)。

我们的目的是通过交换,使得网格变为如下排列(称为正确排列):

1 2 3
4 5 6
7 8 x
例如,示例中图形就可以通过让 x 先后与右、下、右三个方向的数字交换成功得到正确排列。

交换过程如下:

1 2 3 . . . 1 2 3 . . . 1 2 3 . . . 1 2 3
x 4 6 . . . 4 x 6 . . . 4 5 6 . . . 4 5 6
7 5 8 . . . 7 5 8 . . . 7 x 8 . . . 7 8 x
现在,给你一个初始网格,请你求出得到正确排列至少需要进行多少次交换。

输入格式
输入占一行,将 3×3 的初始网格描绘出来。

例如,如果初始网格如下所示:

1 2 3
x 4 6
7 5 8
则输入为:1 2 3 x 4 6 7 5 8

输出格式
输出占一行,包含一个整数,表示最少交换次数。

如果不存在解决方案,则输出 −1。

输入样例:
2 3 4 1 5 x 7 6 8
输出样例
19


做法:

1、普通bfs(时耗:1741ms)

#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>

using namespace std;

int bfs(string state)
{
    queue<string> q;
    unordered_map<string, int> d;

    q.push(state);
    d[state] = 0;

    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

    string end = "12345678x";
    while (q.size())
    {
        auto t = q.front();
        q.pop();

        if (t == end) break;

        int distance = d[t];
        int k = t.find('x');
        int x = k / 3, y = k % 3;
        for (int i = 0; i < 4; i ++ )
        {
            int a = x + dx[i], b = y + dy[i];
            if (a >= 0 && a < 3 && b >= 0 && b < 3)
            {
                swap(t[a * 3 + b], t[k]);
                if (!d.count(t))
                {
                    d[t] = distance + 1;
                    q.push(t);
                }
                swap(t[a * 3 + b], t[k]);
            }
        }
    }

    return d[end];
}

int main()
{
    char s[2];

    string start;
    for (int i = 0; i < 9; i ++ )
    {
        cin >> s;
        start += *s;
    }

    int nums = 0;
    for(int i = 0; i < 9; i++)
    {
        if(start[i] == 'x') continue;
        for(int j = i + 1; j < 9; j++)
        {
            if(start[j] == 'x') continue;
            if(start[j] < start[i]) nums++; //逆序数
        }
    }

    if(nums & 1)    puts("-1");
    else    cout << bfs(start) << endl;

    return 0;
}

2、A*算法(时耗:90ms)

#include<iostream>
#include<unordered_map>
#include<string>
#include<queue>
#include<algorithm>

using namespace std;

typedef pair<int,string> pis;

string start, End = "12345678x";

int f(string state)
{
    int res = 0;
    for(int i = 0; i < state.length(); i++)
        if(state[i] != 'x')
        {
            int t = state[i] - '1';
            res += abs(i / 3 - t / 3) + abs(i % 3 - t % 3);
        }
    return res;
}

int astar()
{
    unordered_map<string,int> d;
    priority_queue<pis, vector<pis>, greater<pis>> q;

    q.push(pis(f(start), start));
    d[start] = 0;

    int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};

    while(!q.empty())
    {
        string u = q.top().second;
        q.pop();

        if(u == End)    break;

        int pos = u.find('x');
        int x = pos / 3, y = pos % 3;
        for(int i = 0; i < 4; i++)
        {
            int xx = x + dx[i], yy = y + dy[i];
            if(xx < 0 || xx > 2 || yy < 0 || yy > 2)    continue;

            string v = u;
            swap(v[pos], v[xx * 3 + yy]);

            if(!d.count(v) || d[v] > d[u] + 1)
            {
                d[v] = d[u] + 1;
                q.push(pis(d[v] + f(v), v));
            }
        }
    }

    return d[End];
}

int main()
{
    char ch;
    for(int i = 0; i < 9; i++)  cin >> ch, start += ch;

    int nums = 0;
    for(int i = 0; i < 9; i++)
    {
        if(start[i] == 'x') continue;
        for(int j = i + 1; j < 9; j++)
        {
            if(start[j] == 'x') continue;
            if(start[j] < start[i]) nums++; //逆序数
        }
    }

    if(nums & 1)    puts("-1");
    else    cout << astar() << endl;

    return 0;
}

3、双向bfs(时耗:62ms)

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<unordered_map>
#include<stack>
#include<queue>
#include<string>
#include<vector>
#include<algorithm>
#define ll long long
#define mem(a) memset(a,0,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define inf 0x3f3f3f3f
#define endl '\n'
#define cyes cout<<"yes"<<endl
#define debug(x) cout<<"-----"<<x<<endl
using namespace std;

string start, End = "12345678x";

int extend(queue<string> &q, unordered_map<string, int> &d1, unordered_map<string,int> &d2)
{
    static int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};

    for(int k = 0, sk = q.size(); k < sk; k++)
    {
        string u = q.front();
        q.pop();

        int pos = u.find('x');
        int x = pos / 3, y = pos % 3;

        for(int i = 0; i < 4; i++)
        {
            int xx = x + dx[i], yy = y + dy[i];
            if(xx < 0 || xx > 2 || yy < 0 || yy > 2)    continue;
            string v = u;
            swap(v[pos], v[xx * 3 + yy]);

            if(d1.count(v)) continue;
            if(d2.count(v)) return d1[u] + 1 + d2[v];

            d1[v] = d1[u] + 1;
            q.push(v);
        }
    }
    return -1;
}

int bfs()
{
    queue<string> qa, qb;
    unordered_map<string,int> da, db;
    qa.push(start); da[start] = 0;
    qb.push(End); db[End] = 0;

    while(qa.size() && qb.size())
    {
        int t;
        if(qa.size() <= qb.size())  t = extend(qa, da, db);
        else    t = extend(qb, db, da);

        if(t != -1) return t;
    }
    return -1;
}

int main()
{
    char ch;
    for(int i = 0; i < 9; i++)  cin >> ch, start += ch;

    int nums = 0;
    for(int i = 0; i < 9; i++)
    {
        if(start[i] == 'x') continue;
        for(int j = i + 1; j < 9; j++)
        {
            if(start[j] == 'x') continue;
            if(start[j] < start[i]) nums++;
        }
    }

    if(nums & 1)    puts("-1");
    else    cout << bfs() << endl;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值