首AC!
原题链接:9553.马遍历棋盘2024-03-02 15:29:51
发布于:广东
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node{
	int x,y;//坐标
	int step;//当前步数 
};
queue<node> q;
int n,m,x,y;
int dx[9]={0,-2,-2,-1,1,2,2,1,-1},dy[9]={0,-1,1,2,2,1,-1,-2,-2};
int d[405][405];
bool vis[405][405],flag=1;
void bfs(){
	q.push({x,y,0});
	d[x][y]=0;
	vis[x][y]=1;
	while(!q.empty()){
		node p=q.front();
		for(int i=1;i<=8;++i){
			int tx=p.x+dx[i],ty=p.y+dy[i];
			if(!vis[tx][ty]&&tx>=1&&tx<=n&&ty>=1&&ty<=m){
				flag=0;
				q.push({tx,ty,p.step+1});
				d[tx][ty]=p.step+1;
				vis[tx][ty]=1;
			}
		}
		q.pop();
	}
}
int main(){
	cin>>n>>m>>x>>y;
	bfs();//从起点开始 
	if(flag){
		cout<<-1;
		return 0;
	}
	for(int i=1;i<=n;++i){
		for(int j=1;j<=m;++j){
			printf("%-5d",d[i][j]);
		}
		cout<<endl;
	}
	return 0;
}
这里空空如也






有帮助,赞一个