CSU1224古怪的象棋(典型bfs)

版权声明:仅供研究,转载请注明出处。 https://blog.csdn.net/CSUstudent007/article/details/83826414

 思路:

经典bfs,无脑让马走八个方向就行,注意别出边界。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<math.h>
#include<cstdlib>
#include<queue>
#include<map>
#include<set>
using namespace std;
int n,m;
int sx,sy,fx,fy;
struct node{
	int x,y;
	int step;
}now,temp,nextt;
int moves[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
int vis[25][25];
queue<node> q;
void bfs(){
	while(!q.empty()) q.pop();
	memset(vis,0,sizeof(vis));
	now.x=sx,now.y=sy;
	vis[sx][sy]=1;
	now.step=0;
	q.push(now);
	while(!q.empty()){
		temp=q.front();
		q.pop();
		if(temp.x==fx&&temp.y==fy){
			printf("%d\n",temp.step);
			return ;
		}
		for(int i=0;i<8;i++){
			nextt.x=temp.x+moves[i][0];
			nextt.y=temp.y+moves[i][1];
			if(nextt.x>=0&&nextt.y>=0&&nextt.x<n&&nextt.y<m&&!vis[nextt.x][nextt.y]){
				nextt.step=temp.step+1;
				vis[nextt.x][nextt.y]=1;
				q.push(nextt);
			}
		}
	}
	printf("-1\n");
	return ;
}
int main(){
	while(scanf("%d%d%d%d%d%d",&n,&m,&sx,&sy,&fx,&fy)!=EOF){
		bfs();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CSUstudent007/article/details/83826414