zufeoj_Knight Moves

题目链接:http://acm.ocrosoft.com/problem.php?cid=1222&pid=25


题目描述

输入n代表有个n*n的棋盘,输入开始位置的坐标和结束位置的坐标,问一个骑士朝棋盘的八个方向走马字步,从开始坐标到结束坐标可以经过多少步。

输入

首先输入一个n,表示测试样例的个数。

每个测试样例有三行。

第一行是棋盘的大小L(4≤L≤300);

第二行和第三行分别表示马的起始位置和目标位置(0~L-1)。


输出

马移动的最小步数,起始位置和目标位置相同时输出0。


样例输入

3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1

样例输出

5
28
0


基础BFS

#include<bits/stdc++.h>
using namespace std;
int n;
int vis[301][301];
int dir[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}};
int stx,sty,enx,eny;
struct MM{
	int x,y;
	int step;
};
void bfs(int sx,int sy){
	queue<MM> q;
	memset(vis,0,sizeof(vis));
	MM now,nextt;
	now.x=sx;
	now.y=sy;
	now.step=0;
	vis[now.x][now.y]=1;
	q.push(now);
	while(!q.empty()){
		now=q.front();
		q.pop();
		if(now.x==enx&&now.y==eny){
			cout<<now.step<<endl;
		 	return;	
		}
		for(int i=0;i<8;i++){
			nextt.x=now.x+dir[i][0];
			nextt.y=now.y+dir[i][1];
			if(!vis[nextt.x][nextt.y]&&nextt.x>=0&&nextt.y>=0&&nextt.x<n&&nextt.y<n){
				nextt.step=now.step+1;
				q.push(nextt);
				vis[nextt.x][nextt.y]=1;
			}
		}
	}
}
int main(){
	int T;
	cin>>T;
	while(T--){
		cin>>n;
		cin>>stx>>sty>>enx>>eny;
		if(stx==enx&&sty==eny){
			cout<<"0"<<endl;
		}else{
			bfs(stx,sty);
		}
	}
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值