跳到正文

题解

骑士精神

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

文章信息

发布
2019年10月18日
收录
2025年12月12日
更新
2026年10月31日
篇幅
约 4 分钟
获赞
2
题目
P2324

版本

  1. v1当前

一道很好的练习搜索的题目

可以用到A*和迭代加深的搜索算法。发现用了A_star后的代码,运行效率确实优化了很多

解释都在代码中。

C++
//一道很好的A*的模板题:骑士精神

//所谓的估价函数也可以理解为一种最坏或最优的情况。
//也就是在当前搜索的基础上,如果当前的答案加上最好的情况
//都达不到要求,那么就可以跳过。
//其实我觉得估价函数也可以看做剪枝的一种 
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
inline int read()//快速读入
{
	int x=0;
	int f=1;
	char ch=getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch=='-')
		f=-1;
		ch=getchar();
	}
	while(ch>='0' && ch<='9')
	{
		x=x*10+ch-'0';
		ch=getchar();
	}
	return x*f;
}
int mp[15][15];
int flag=0;
int stx;
int sty;
int dx[]={0,1,1,-1,-1,2,2,-2,-2};
int dy[]={0,2,-2,2,-2,1,-1,1,-1};
int goal[7][7]={//将我们的目标状态通过达标的方式打出来。 
    {0,0,0,0,0,0},
    {0,1,1,1,1,1},
    {0,0,1,1,1,1},
    {0,0,0,2,1,1},
    {0,0,0,0,0,1},
    {0,0,0,0,0,0}
}; 
int evaluate()
{
	int cnt=0;
	for(int i=1;i<=5;i++)
	{
		for(int j=1;j<=5;j++)
		{
			if(mp[i][j]!=goal[i][j])
			cnt++;
		}
	} 
	return cnt;//估价函数,也就相当于是最坏情况了。 
}
void A_star(int dep,int x,int y,int maxdep)
{
	if(dep==maxdep)
	{
		if(!evaluate())
		{
			flag=1;			
		}
		return;
	}
	for(int i=1;i<=8;i++)
	{
		int nowx=x+dx[i];
		int nowy=y+dy[i];
		if(nowx<=0 || nowy>5 || nowy<=0 || nowx>5)
		continue;//判断边界 
		swap(mp[x][y],mp[nowx][nowy]);//这里直接用swap交换操作,又快又方便 
		if(dep+evaluate()<=maxdep)
		{
			A_star(dep+1,nowx,nowy,maxdep);
		}
		swap(mp[x][y],mp[nowx][nowy]);//回溯操作。
		//这样能保证所有的状态都能查询到 
	}
}
int main()
{
	int T;
	T=read();
	while(T--)
	{
		flag=0;
		for(int i=1;i<=5;i++)
		{
			for(int j=1;j<=5;j++)
			{
				char ch;
				cin>>ch;
				if(ch=='*')
				{
					mp[i][j]=2;
			    	stx=i;
			    	sty=j;
				}
				else
				mp[i][j]=ch-'0';
			}//把字符转成数字,同时记录起点的坐标 
		}
		if(!evaluate())
		{
			printf("0\n");//特判 
			continue;//如果一开始就搜索正确,那么直接输出答案 
		}
		for(int i=1;i<=15;i++)
		{//这里有可能是个迭代加深的过程,就是在判断当前深度是否可行
		//从而提高了代码的运行速率 
		//真是个好方法 
			A_star(0,stx,sty,i);//按照最大的深度限制就搜索一下 
			if(flag==1)//如果搜索成功就输出答案。 
			{
				printf("%d\n",i);
				break;
			}
		}
		if(flag==0)//搜索不成功就输出-1; 
		printf("-1\n");
	}
	return 0;
} 
原文
存档评论2 条抓取于