好马不吃回头草题解!

仅供参考!!

#include<bits/stdc++.h>
using namespace std;
struct Point{
	int x,y;
}st,ed;
int n;
int dx[]={1,2,2,1};
int dy[]={2,1,-1,-2};//不回头!!!!!!
int bfs(){
	/*
	初始化queue<Point>que/vis(设为0)/step
	然后memset(step,-1,step占据的空间)
	标记起点步数为0,并设为已访问
	*/
	while(/*队列不为空*/)){
		//取、丢队头
		if(/*到达终点*/){
			return step[pt.x][pt.y];//返回步数
		}
		for(int i=0;i<4;i++){
			int x=pt.x+dx[i];
			int y=pt.y+dy[i];
			if(/*未超出边界且未访问*/){
				vis[x][y]=1;
		    	step[x][y]=step[pt.x][pt.y]+1;
		    	que.push((Point){x,y});
			}
		}
	}
	return -1;
}
int main(){
	/*
	输入
	*/
	cout<<bfs();//输出结果
	return 0;
}

叫我大好人!代码仅供参考,禁止直抄!(虽然我管不着)

我做出来啦!

#include<bits/stdc++.h>
using namespace std;
int n,sx,sy,fx,fy,vis[1005][1005];
int dx[4]={1,2,2,1};
int dy[4]={-2,-1,1,2};
struct node{
	int x,y,step;
};
void bfs(){
	queue<node> que;
	que.push({sx,sy,0});
	vis[sx][sy]=0;
	while(que.size()){
		node head=que.front();
		que.pop();
		if(head.x==fx and head.y==fy)
		{
			cout<<head.step;
			return;
		}
		for(int i=0;i<4;i++)
		{
			int nx=head.x+dx[i],ny=head.y+dy[i];
			if(nx>0 and nx<=n and ny>0 and ny<=n and vis[nx][ny]==-1)
			{
				vis[nx][ny]=1;
				que.push({nx,ny,head.step+1});
			}
		}
	}
	cout<<"-1";
	 
}
int main(){
	memset(vis,-1,sizeof vis);
	cin>>n;
	cin>>sx>>sy;
	cin>>fx>>fy;
	bfs();
}

啊?

6。