简述
经典的搜索问题,这道题用普通的bfs也能过,但是效率远不如 A*。就是一个3 * 3 的华容道,其中有一个空格(‘0’)你要把题目给的形式变成目标形式"123804765".
思路
dist [ i ] 数组代表的是 i 到终点的估价函数 f + 起点到 i 真实距离 g,当 f = 0 的时候就是朴素bfs。估价函数的定义:f 的值必须小于等于 i 到终点的真实值
代码实现
#include<bits/stdc++.h>
#define PII pair<int,int>
#define PIS pair<int,string>
using namespace std;
string ed = "123804765";
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
PII pos[9] = {{0,0},{0,1},{0,2},{1,2},{2,2},{2,1},{2,0},{1,0}};
// 估价函数定义为 当前字符串 到 目标字符串 的所有曼哈顿距离之和
int f(string s){
int res = 0;
for(int i = 0;i < 9; i++)
if(s[i] != '0'){
auto [x,y] = pos[s[i]-'1'];
res += abs(x/3-i/3) + abs(y%3-i%3);
}
return res;
}
// 宽搜
int bfs(string s) {
unordered_map<string,int> dist;
// 必须 pair<int,string> 按照第一关键字排序 pair<string,int> 是错误的
priority_queue<PIS,vector<PIS>,greater<PIS>> q;
dist[s] = 0;
// 一开始的真实距离为 0
q.push({f(s),s});
while (q.size()) {
auto t = q.top(); q.pop();
s = t.second;
if (s == ed) return dist[s];
int x,y;
for(int i = 0;i < 9; i++)
if(s[i] == '0'){
x = i/3;
y = i%3;
}
for(int i = 0;i < 4; i++){
string ne = s;
int nx = x+dx[i],ny = y+dy[i];
// 不合法的位置
if(nx < 0 || ny < 0 || nx >= 3 || ny >= 3) continue;
swap(ne[nx*3+ny],ne[x*3+y]);
// ( 如果下一个状态没有出现过 || 当前点到下一个状态的距离更短 )更新
if(!dist.count(ne) || dist[s]+1 < dist[ne]){
dist[ne] = dist[s]+1;
// 把 f + g 放进堆内
q.push({dist[ne]+f(ne),ne});
}
}
}
return -1;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
string s; cin>>s;
cout<<bfs(s);
return 0;
}