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

本文探讨了一种解决特定问题的高效算法策略——逆向BFS。通过对比正向搜索,逆向BFS能显著提高搜索效率,尤其适用于数据量不大但状态复杂的情形。文章深入分析了逆向BFS的工作原理,并提供了详细的代码实现,展示了如何利用这一策略来优化搜索过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目很有趣,正着跑一遍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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值