跳到正文

个人记录

骑士精神 IDA*

HUjingwei约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年9月6日
收录
2026年11月3日
更新
2026年11月22日
篇幅
约 4 分钟

版本

  1. v1当前

IDA* = ID + A*

以 骑士精神 为例,总代码:

C++
#include<bits/stdc++.h>
using namespace std;
string a;
struct node{
	string x;
	int n;
	int steps;
};
queue<node> q;
map<string,bool> mp;
int find_1(string t,char x){
	for(int i=0;i<t.length();i++)
		if(a[i]==x)
			return i;
}
int d[]={-3,-1,1,3};
node T;
string t,s;
int now,step,tx;
int main(){
	cin>>a;
	q.push(node{a,find_1(a,'0'),0});
	while(!q.empty()){
		T=q.front();
		t=T.x;
		now=T.n;
		step=T.steps;
		q.pop();
		//cout<<t<<' '<<now<<' '<<step<<endl;
		if(t=="123804765"){
			cout<<step;
			return 0;
		}for(int i=0;i<4;i++){
			s=t;
			tx=now+d[i];
			swap(s[now],s[tx]);
			if(tx>=0&&tx<=8&&!mp[s]&&((d[i]==1&&tx!=3&&tx!=6)||(d[i]==-1&&tx!=2&&tx!=5)||d[i]==3||d[i]==-3)){
				mp[s]=1;
				q.push(node{s,tx,step+1});
			}
		}
	}
	return 0;
}
C++
#include<bits/stdc++.h>
using namespace std;
const int Max=1e9;
int ret;
char Map[5][5],res[5][5]={{'1','1','1','1','1'},{'0','1','1','1','1'},{'0','0','*','1','1'},{'0','0','0','0','1'},{'0','0','0','0','0'}};
int sx,sy;
int dx[8]={1,1,-1,-1,2,2,-2,-2};
int dy[8]={2,-2,2,-2,1,-1,1,-1};
int find(){
	int cnt=0;
	for(int i=0;i<5;i++)
		for(int j=0;j<5;j++)
			if(Map[i][j]!=res[i][j])
				cnt++;
	return cnt;
}
void dfs(int x,int y,int xx,int yy,int step)
{
	int h=find();
	if(h+step>15) return;
	if(h==0){
		ret=min(ret,step);
		return;
	}
	for(int i=0;i<8;i++){
		int tx=x+dx[i],ty=y+dy[i];
		if(tx>=0&&ty>=0&&tx<=4&&ty<=4&&(xx!=tx||yy!=ty)){
			swap(Map[tx][ty],Map[x][y]);
			dfs(tx,ty,x,y,step+1);
			swap(Map[tx][ty],Map[x][y]);
		}
	}
}

int main(){
	int TT;
	char T;
	cin>>TT;
	while(TT--){
		for(int i=0;i<5;i++){
			for(int j=0;j<5;j++){
				cin>>T;
				Map[i][j]=T;
				if(Map[i][j]=='*'){
					sx=j;sy=i;
				}
			}
		}
		ret=Max;
		dfs(sy,sx,0,0,0);
		if(ret==Max) cout<<-1<<endl;
		else cout<<ret<<endl;
	}
	return 0;
}

ID-DFS

规定一个搜索深度以减去多余部分 题中所给的最高搜索层次为15(因为一共就只有16位)

A*

提前以最优的可能情况走完一次求最值

原文