当前位置:网站首页>信息学奥赛一本通(1257:Knight Moves)
信息学奥赛一本通(1257:Knight Moves)
2022-08-02 20:02:00 【橙子教师】
1257:Knight Moves
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 6149 通过数: 3100
【题目描述】
输入nn代表有个n×n的棋盘,输入开始位置的坐标和结束位置的坐标,问一个骑士朝棋盘的八个方向走马字步,从开始坐标到结束坐标可以经过多少步。

【输入】
首先输入一个nn,表示测试样例的个数。
每个测试样例有三行。
第一行是棋盘的大小L(4≤L≤300);
第二行和第三行分别表示马的起始位置和目标位置(0..L−1)。
【输出】
马移动的最小步数,起始位置和目标位置相同时输出00。
【输入样例】
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1【输出样例】
5
28
0【分析】
马走日,8个方向,方向数组(1,2),(1,-2),(-1,2),(-1,-2),(2,1),(2,-1),(-2,1),(-2,-1)。
【参考代码】
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=310;
struct node
{
int x,y;
int t;
};
int sx,sy; //起点坐标
int ex,ey; //终点坐标
int l; //棋盘大小
int dx[]={1,1,-1,-1,2,2,-2,-2}; //方向数组
int dy[]={2,-2,2,-2,1,-1,1,-1};
bool vis[N][N]; //访问数组
void bfs()
{
queue <node> q; //申请队列
node st;
st.x=sx;
st.y=sy;
st.t=0;
q.push(st); //起点入队
while(!q.empty())
{
node nt=q.front();
if(nt.x==ex && nt.y==ey)
{
cout<<nt.t<<endl;
break;
}
for(int i=0;i<8;i++)
{
int nx=nt.x+dx[i];
int ny=nt.y+dy[i];
if(vis[nx][ny]==false && nx>=0 && nx<l && ny>=0 && ny<l)
{
vis[nx][ny]=true;
node tmp;
tmp.x=nx;
tmp.y=ny;
tmp.t=nt.t+1;
q.push(tmp);
}
}
q.pop();
}
return;
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(vis,false,sizeof(vis));
cin>>l;
cin>>sx>>sy>>ex>>ey;
vis[sx][sy]=true;
bfs();
}
}边栏推荐
猜你喜欢

B站HR对面试者声称其核心用户都是生活中的Loser

Kali命令ifconfig报错command not found

MySQL安装时一直卡在starting server

Mysql安装流程 【压缩版】

Shell: conditional statements
![LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路](/img/dc/ba5a0c3f6a58283d79c5916376e49e.png)
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路

基于 outline 实现头像剪裁以及预览

VMware虚拟机无法上网

当TIME_WAIT状态的TCP正常挥手,收到SYN后…

Flutter with internationalized adapter automatically generated
随机推荐
Introduction of uncommon interfaces of openlayers
新增指令 v-memo
实现客户服务自助,打造产品知识库
Golang source code analysis: juju/ratelimit
【 LeetCode 】 1374. Generate each character string is an odd number
Flutter自带国际化适配自动生成方案
MySQL安装时一直卡在starting server
postgresql autovaccum自动清理
Parse the commonly used methods in the List interface that are overridden by subclasses
V - memo new instructions
The so-called fighting skill again gao also afraid of the chopper - partition, depots, table, and the merits of the distributed
Mysql安装流程 【压缩版】
什么是乙二醇二乙酸酯(EGDA)?
Office2021 安装MathType
Redis cluster configuration
Cannot find declaration to go to
J9 digital theory: the Internet across chain bridge has what effect?
SCANIA SCANIA OTL tag is introduced
所谓武功再高也怕菜刀-分区、分库、分表和分布式的优劣
有效解决MySQL报错:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO/YES)