三、搜索和二分 [Cloned] T - 搜索

本文介绍了一种使用广度优先搜索(BFS)解决国际象棋中骑士从一个位置移动到另一个位置所需最少步数的问题。通过创建节点结构、定义骑士可能的移动方式,并利用队列进行遍历,确保找到最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:

Background 
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move knights from one position to another so fast. Can you beat him? 
The Problem 
Your task is to write a program to calculate the minimum number of moves needed for a knight to reach one point from another, so that you have the chance to be faster than Somurolov. 
For people not familiar with chess, the possible knight moves are shown in Figure 1. 

题意:

依然是移动象棋的马走日问题,问从一个点到另一个点最少需要多少步骤。

题解:

可以是说是跟前边两个基本类似,区别就是在于因为要找最少的步骤,所以需要用广搜来搜索,创建队列不断出队然后查找然后队,同时检查要查找的点是否访问过以及是否超出边界,别的就是基本的广搜了。

代码:AC

#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef struct
{
	int x,y;
	int step;
}node;
int visit[1000][1000];
int fx[]={-2,-2,-1,-1,2,2,1,1};
int fy[]={-1,1,-2,2,-1,1,-2,2};
int l;
queue<node>Q;
node start,end;
int check(int i,int j)
{
	if(i>=0&&j>=0&&i<l&&j<l&&visit[i][j]==0)
		return 1;
	return 0;
}

int bfs()
{
	start.step=0;
	Q.push(start);
	visit[start.x][start.y]=1;
	node a,next;
	while(!Q.empty())
	{
		a=Q.front();
		Q.pop();
		int i;
		for(i=0;i<8;i++)
		{
			next.x=a.x+fx[i];
			next.y=a.y+fy[i];
			if(check(next.x,next.y))
			{
				next.step=a.step+1;
				if(next.x==end.x&&next.y==end.y)
					return next.step;
				Q.push(next);
				visit[next.x][next.y]=1;
			}
		}
	}
	return -1;
}
int main()
{
	int t,i,j;
	cin>>t;
	while(t--)
	{
		cin>>l;
		for(i=0;i<l;i++)
			for(j=0;j<l;j++)
				visit[i][j]=0;
		cin>>start.x>>start.y;
		cin>>end.x>>end.y;
		if(start.x==end.x&&start.y==end.y)
		{
			cout<<"0"<<endl;
			continue;
		}
		else
		{
			while(!Q.empty())
				Q.pop();
			cout<<bfs()<<endl;
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值