当前位置:网站首页>信息学奥赛一本通(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();
}
}
边栏推荐
- 解析List接口中的常用的被实现子类重写的方法
- PyTorch分布式backends
- 牛客题目——滑动窗口的最大值、矩阵最长递增路径、顺时针旋转矩阵、接雨水问题
- AI Scientist: Automatically discover hidden state variables of physical systems
- golang源码分析:time/rate
- OP-5,输入/输出信号范围-一信号处理能力
- 一些不错的博主
- Introduction of uncommon interfaces of openlayers
- GNN教程:图神经网络基础知识!
- LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
猜你喜欢
随机推荐
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
网络协议介绍
六石管理学:入门机会只有一次,先把产品做好
Redis 5 种数据结构及对应使用场景
成为黑客不得不学的语言,看完觉得你们还可吗?
ABAP语法小复习
J9数字货币论:识别Web3新的稀缺性:开源开发者
Redis cluster configuration
软件测试分类
扫码预约 | 观看Apache Linkis数据处理实践以及计算治理能力
Leetcode刷题——字符串相加相关题目(415. 字符串相加、面试题 02.05. 链表求和、2. 两数相加)
网上那么多教人赚钱的方法,但是你实际上是靠什么赚钱的呢?
太魔人招新啦|快来加入我们吧!
golang 源码分析:uber-go/ratelimit
Silver circ: letter with material life insurance products should be by the insurance company is responsible for the management
MySQL安装(详细,适合小白)
SQL Server数据类型转换函数cast()和convert()详解
银保监会:人身险产品信披材料应由保险公司总公司统一负责管理
Thread线程类基本使用(上)
"A daily practice, happy water problem" 1374. Generate a string with an odd number of each character