首页 > 其他 > 详细

AOJ 0121 Seven Puzzle bfs

时间:2020-12-13 23:51:41      阅读:29      评论:0      收藏:0      [点我收藏+]
//https://blog.csdn.net/qq_33929112/article/details/52454779
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<map>
#include<string>
#include<algorithm>
using namespace std;

map<string, int> dp;
int dir[4] = {-1,1,4,-4}; // 4 个方向

bool in(int a, int b)
{
    if(a+b < 0 || a+b > 7) return false;
    if(a == 3 && b == 1 || a == 4 && b == -1) return false;
    return true;
}

void bfs()
{
    queue<string> que;
    que.push("01234567");
    dp["01234567"] = 0;
    while(!que.empty())
    {
        string s = que.front();
        que.pop();
        int index;
        for(int i = 0;  i < 8; i++) if(s[i] == ‘0‘) index = i;
        for(int i = 0; i < 4; i++)
        {
            if(in(index, dir[i]))
            {
                string tmp = s;
                int ni = index+dir[i];
                swap(tmp[ni], tmp[index]);
                if(dp.find(tmp) == dp.end())  //找不到
                {
                    dp[tmp] = dp[s]+1;
                    que.push(tmp);
                }
            }
        }
    }
}


int main()
{
    bfs();
    string s;
    while(getline(cin, s))
    {
        s.erase(remove(s.begin(), s.end(), ‘ ‘), s.end());
        cout << dp[s] << endl;
    }
    system("pause");
    return 0;
}

AOJ 0121 Seven Puzzle bfs

原文:https://www.cnblogs.com/znk97/p/14130840.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!