hdu1372 Knight Moves

本文介绍了一种使用广度优先搜索(BFS)算法来解决国际象棋中骑士从一个位置走到另一个位置最少步数的问题。通过定义骑士的移动方式,并采用节点结构存储位置信息,实现了对棋盘的有效遍历。

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

需要国际象棋的知识,棋盘是1-8,a-h,骑士就是马啦,走的是2*3的格子的对角线,那么就是有八个方位


#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
#define N 105
using namespace std;

struct node{
	int x,y,step; 
};

int n,m;
int vis[N][N],map[N][N];
int ex,ey;
char s1[10],s2[10];

int check(int x,int y){
	if(x<=0||x>n||y<=0||y>m||map[x][y])return 1;
	return 0;
}
int bfs(){
	int i;
	queue<node>Q;
	node a,next;
	a.x=s1[0]-'a'+1;
	a.y=s1[1]-'0';
	ex=s2[0]-'a'+1;
	ey=s2[1]-'0';
	//printf("%d %d\n",a.x,a.y);
	a.step=0;
	memset(map,0,sizeof(map));
	map[a.x][a.y]=1;
	Q.push(a);
	while(!Q.empty()){
		//printf("111\n");
	 	a=Q.front();
	 	Q.pop();
	 	if(a.x==ex&&a.y==ey)return a.step;
	 	next.x=a.x+1;
	 	next.y=a.y+2;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	 	next.x=a.x+2;
	 	next.y=a.y+1;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	 	next.x=a.x+2;
	 	next.y=a.y-1;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	 	next.x=a.x+1;
	 	next.y=a.y-2;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	 	next.x=a.x-1;
	 	next.y=a.y+2;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	 	next.x=a.x-2;
	 	next.y=a.y+1;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	 	next.x=a.x-2;
	 	next.y=a.y-1;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	 	next.x=a.x-1;
	 	next.y=a.y-2;
	 	if(next.x==ex&&next.y==ey)return a.step+1;
	 	if(!check(next.x,next.y)){
	 		next.step=a.step+1;
	 		map[next.x][next.y]=1;
	 		Q.push(next);
	 	}
	}
	return 0;
}
int main(){
	n=8;m=8;
	while(scanf("%s%s",s1,s2)!=EOF){
		printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs());
 	}	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值