acwing自我学习笔记--八数码 845

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

using namespace std;

int bfs(string state)
{
    queue<string> q;
    q.push(state);//入队
    unordered_map<string, int> d;//利用hash表标记移动
    d[state] = 0;//初始化状态,标记移动次数为0;

    int distance = 0;
    int dx[] = { 1,0,-1,0 }, dy[] = { 0,1,0,-1 };//上下左右四个方向移动
    string end = "12345678x";
    
    while (q.size())
    {
        auto start = q.front();
        q.pop();//BFS标准流程
        if (start == end)
        {
            return d[start];
        }
        distance = d[start];
        int t = start.find('x');
        for (int i = 0; i < 4; i++)
        {
            int x = dx[i] + t/3, y = dy[i] + t%3;//求出坐标
            if (x >= 0 && x < 3 && y >= 0 && y < 3)
            {
                int a = x * 3, b = y;//x的下一个位置在字符串中的下标:a+b
                swap(start[t], start[a + b]);
                if (!d[start])
                {
                    d[start] = distance + 1;
                    q.push(start);
                }
                swap(start[t], start[a + b]);
            }
        }
    }
    return -1;
}

int main()
{
   
    string state;
    char s;
    for (int i = 0; i < 9; i++)
    {
        cin >> s;
        state += s;
    }
    cout << bfs(state) << endl;

    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值