P1379 八数码难题 绿

题意:在3×3的棋盘上,摆有八个棋子,每个棋子上标有1到8的某一数字。棋盘中留有一个空格,空格用0来表示。目标状态为123804765,找到一种最少步骤的移动方法

a*分析:

估价函数:从当前状态到目标状态,就是曼哈顿距离之和

将bfs优化成a*,用优先队列存储序列以及字符串

代码:

#include<bits/stdc++.h>
using namespace std;
unordered_map<string,int>d;
queue<string>q;
int gx[]={-1,0,0,0,1,2,2,2,1};
int gy[]={-1,0,1,2,2,2,1,0,0};
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int f(string s){ //估价函数: 曼哈顿距离之和
  int res=0;
  for(int i=0; i<9; i++){
    int t=s[i]-'0';
    if(t) res+=abs(i/3-gx[t])+abs(i%3-gy[t]);
  }
  return res;
}
int aStar(string start){
  string end="123804765";
  unordered_map<string,int> d;
  priority_queue<pair<int,string>> q;//大根堆
  q.push({-f(start),start}); d[start]=0;
  while(q.size()){
    auto a=q.top(); q.pop();
    string s=a.second;
    if(s==end) return d[s]; //边界
    int k=s.find('0');
    int x=k/3, y=k%3; //行列坐标
    for(int i=0; i<4; i++){
      int a=x+dx[i], b=y+dy[i];
      if(a<0||a>=3||b<0||b>=3)continue;
      string t=s; swap(t[k],t[a*3+b]); //交换
      if(!d.count(t))//如果没有搜过
        d[t]=d[s]+1, q.push({-(d[t]+f(t)),t});//用负号表示小根堆
    }
  }
}
int main(){
	string s;cin>>s;
	cout<<aStar(s)<<endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值