跳到正文

题解

题解 P2324 【[SCOI2005]骑士精神】

深巷少年与猫约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
题目
P2324

版本

  1. v2当前
  2. v1

题解里的bfs好像大多都是双向搜的,其实单向搜也可以

这道题就是一个A*

我把这个图,跟空格的横纵坐标压成一个string,放在结构体里,每次判断一下是不是到了目标状态,然后用一个map记录一下是否跑过,估价函数就是判断目前状态与目标状态的不同的点的个数,如果这个差距加上目前步数超过了15步,就说明一定跑不到了。

放代码:

C++
#include <bits/stdc++.h>
using namespace std;
map<string,int>s;
int mp[6][6],b[6][6],ans[6][6];
string goal;
int dx[9]={0,1,1,2,2,-1,-1,-2,-2};
int dy[9]={0,2,-2,1,-1,2,-2,1,-1};
string get_char(int x){
	if(x==0){
		return "0";
	}
	if(x==1){
		return "1";
	}
	if(x==2){
		return "2";
	}
	if(x==3){
		return "3";
	}
	if(x==4){
		return "4";
	}
	if(x==5){
		return "5";
	}
}
string lock(int a[6][6],int x,int y){
	string res;
	for(int i=1;i<=5;i++){
		for(int j=1;j<=5;j++){
			res+=get_char(a[i][j]);
		}
	}
	res+=get_char(x);
	res+=get_char(y);
	return res;
}
int get(string res,int step){
	int cnt=0;
	for(int i=1;i<=5;i++){
		for(int j=1;j<=5;j++){
			ans[i][j]=res[(i-1)*5+j-1]-'0';
			if(ans[i][j]!=b[i][j]){
				cnt++;
			}
		}
	}
	if(cnt+step>15){
		return 0;
	}
	else{
		return 1;
	}
}
struct road{
	int step,x,y;
	string sub;
};
void bfs(string fir,int x,int y){
	queue<road>q;
	road st;
	st.step=0;
	st.x=x;
	st.y=y;
	st.sub=fir;
	q.push(st);
	int cnt=0;
	while(!q.empty()){
		road now=q.front();
		q.pop();
		if(now.step>15){
			printf("-1\n");
			return ;
		}
		if(now.sub==goal){
			printf("%d\n",now.step);
			return ;
		}
		if(get(now.sub,now.step)==0) continue;
		for(int i=1;i<=8;i++){
			int nowx=now.x+dx[i];
			int nowy=now.y+dy[i];
			if(nowx<1||nowx>5||nowy<1||nowy>5){
				continue;
			}
			int kkk[6][6];
			for(int i=1;i<=5;i++){
				for(int j=1;j<=5;j++){
					kkk[i][j]=ans[i][j];
				}
			}
			swap(kkk[now.x][now.y],kkk[nowx][nowy]);
			road node;
			node.step=now.step+1,node.x=nowx,node.y=nowy;
			node.sub=lock(kkk,nowx,nowy);
			if(!s[node.sub]){
				s[node.sub]=1;
				q.push(node);
			}
		}
	}
	printf("-1\n");
}
int main(){
	int t;
	scanf("%d",&t);
	b[1][1]=1,b[1][2]=1,b[1][3]=1,b[1][4]=1,b[1][5]=1;
	b[2][1]=0,b[2][2]=1,b[2][3]=1,b[2][4]=1,b[2][5]=1;
	b[3][1]=0,b[3][2]=0,b[3][3]=0,b[3][4]=1,b[3][5]=1;
	b[4][1]=0,b[4][2]=0,b[4][3]=0,b[4][4]=0,b[4][5]=1;
	b[5][1]=0,b[5][2]=0,b[5][3]=0,b[5][4]=0,b[5][5]=0;
	goal=lock(b,3,3);
	while(t--){
		s.clear();
		int sx,sy;
		for(int i=1;i<=5;i++){
			string a;
			cin>>a;
			for(int j=0;j<a.size();j++){
				if(a[j]=='0'){
					mp[i][j+1]=0;
				}
				else if(a[j]=='1'){
					mp[i][j+1]=1;
				}
				else{
					mp[i][j+1]=0;
					sx=i;
					sy=j+1;
				}
			}
		}
		string fir=lock(mp,sx,sy);
		bfs(fir,sx,sy);
	}
	return 0;
}
原文