题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入输出格式
输入格式:一行四个数据,棋盘的大小和马的坐标
输出格式:一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
输入输出样例
输入样例#1:
复制
3 3 1 1
输出样例#1: 复制
0 3 2 3 -1 1 2 1 4
#include<bits/stdc++.h> using namespace std; struct pos { int x; int y; }; int mark[405][405],dx[]= {2,2,1,-1,-2,-2,-1,1},dy[]= {1,-1,-2,-2,-1,1,2,2},n,m; queue<pos>q; void bfs(int sx,int sy) { int tx,ty; int x,y; q.push(pos{sx,sy}); mark[sx][sy]=0; while(!q.empty()) { x=q.front().x; y=q.front().y; q.pop(); for(int i=0; i<8; i++) { tx=x+dx[i]; ty=y+dy[i]; if(tx<1||ty<1||tx>n||ty>m||mark[tx][ty]+1)continue; q.push(pos{tx,ty}); mark[tx][ty]=mark[x][y]+1; } } } int main() { int a,b; memset(mark,-1,sizeof(mark)); cin>>n>>m>>a>>b; bfs(a,b); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { printf("%-5d",mark[i][j]); } cout<<endl; } return 0; }