当前位置:网站首页>七月第一周
七月第一周
2022-07-07 21:50:00 【zjsru_Beginner】
骑士移动
题目描述:写程序,计算骑士从一个位置移动到另一个位置所需的最少移动次数。骑士移动的规则如下如所示。

每一次跳动,都可以有八种选择,经过多次正确选择后可以找到一个最近的路程。
算法设计:
这是一个求最短距离的问题,可以使用queue进行广度优先搜索步骤,现将起点放入队列,如果队列不空,则对头出对,否则扩展8个方向,如果找到目标,则立即返回步长+1并放入队列,标记其已访问,如果骑士的当前位置为(x,y),则移动时当前位置坐标加上偏移量即可。
输入:
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
输出:
5
28
0
代码:
#include<bits/stdc++.h>
int size ;
struct status{ #结构体
int x;
int y;
int step;
}q[100006];
int vec[8][2]={
{-2,-1},{-1,-2},{-2,1},{-1,2},{2,-1},{1,-2},{2,1},{1,2}}; #方向
int is[333][333];
void bfs(int sx,int sy,int ex,int ey){ #广度优先搜索
int head =0,tail=0;
memset(is,0,sizeof(is));
q[tail].x=sx;
q[tail].y=sy;
is[sx][sy]=1;
tail++;
while (head<tail){
if (q[head].x==ex&&q[head].y==ey){
printf("%d\n",q[head].step);
break ;
}
for(int i=0;i<8;i++){ #对各个方向进行遍历
int nx=q[head].x+vec[i][0];
int ny=q[head].y+vec[i][1];
int step=q[head].step;
if (nx>=0&&nx<size&&ny>=0&&ny<size&&is[nx][ny]==0){
q[tail].x=nx;
q[tail].y=ny;
q[tail].step=step+1;
is[nx][ny]=1;
tail++;
}
}
head ++;
}
}
int main(){
int k;
scanf("%d",&k);
int sx,sy,ex,ey;
while (k--){ #对每个要实现最短距离的目标进行遍历
scanf("%d",&size);
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
bfs(sx,sy,ex,ey);
}
return 0;
}
YJG
边栏推荐
- Clean C disk
- leetcode-520. 检测大写字母-js
- PCL . VTK files and Mutual conversion of PCD
- Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020
- Installing vmtools is gray
- Network security sqlmap and DVWA explosion
- ./ setup. Insufficient sh permission
- 微信论坛交流小程序系统毕业设计毕设(2)小程序功能
- What does the model number of asemi rectifier bridge kbpc1510 represent
- 线上面试,该如何更好的表现自己?这样做,提高50%通过率~
猜你喜欢

Wechat forum exchange applet system graduation design (2) applet function

知识点滴 - PCB制造工艺流程

微生物健康網,如何恢複微生物群落

Are the microorganisms in the intestines the same as those on the skin?

Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020

ArcGIS: two methods of attribute fusion of the same field of vector elements

Gbu1510-asemi power supply special 15A rectifier bridge gbu1510

Brush question 4

JMeter-接口自动化测试读取用例,执行并结果回写
![[record of question brushing] 3 Longest substring without duplicate characters](/img/44/1cd8128d93c9c273e0f4718d84936e.png)
[record of question brushing] 3 Longest substring without duplicate characters
随机推荐
OC variable parameter transfer
PMP项目管理考试过关口诀-1
GEE(三):计算两个波段间的相关系数与相应的p值
Brush question 6
Network security - phishing
网络安全-联合查询注入
Sword finger offer 63 Maximum profit of stock
微信论坛交流小程序系统毕业设计毕设(3)后台功能
Brush question 4
ArcGIS:字段赋值_属性表字段计算器(Field Calculator)依据条件为字段赋值
2021-01-11
Network security sqlmap and DVWA explosion
Network security CSRF
成年人只有一份主业是要付出代价的,被人事劝退后,我哭了一整晚
Network security -beef
Why is network i/o blocked?
I wish you all the best and the year of the tiger
V20变频器手自动切换(就地远程切换)的具体方法示例
Wechat forum exchange applet system graduation design completion (1) development outline
QT graphicsview graphical view usage summary with flow chart development case prototype