AOJ0121-Seven Puzzle( BFS逆向思维+map去重)

1 篇文章 0 订阅

题目很有趣,正着跑一遍BFS慢的要死,看了题解发现可以逆向搜,因为BFS本身是双向的,逆向的话直接存了所有情况的状态,而且数据量不大, 打个表直接输出也是美滋滋。

参考的博客

#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
using namespace std;
const int maxn = 1000+5;
typedef long long ll;
string s;
map<string,int > mp;
queue<string> q;
int d[] = {1,-1,4,-4};

void bfs(){
    q.push("01234567");
    while(!q.empty()){
        string s1 = q.front();
        q.pop();
        int pos = s1.find('0');
        for(int i = 0;i < 4;i++){
            int x = pos + d[i];
            if(x>=0&&x<8&&(!(pos==3&&i==0)&&!(pos==4&&i==1))){
                string u = s1;
                swap(u[pos],u[x]);
                if(mp[u]==0){
                    mp[u]=mp[s1]+1;
                    q.push(u);
                }
            }
        }
    }
    return;
}

int main() {
    bfs();
    mp["01234567"] = 0;
    while(1){
        s = "";
        int a = 8,b;
        while(a--){
            if(!(cin>>b)) return 0;
            s += b+'0';
        }
        cout<<mp[s]<<endl;
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值