题目链接
很适合做bfs模板题的一道题,用stl中的队列和pair解决.
要是不看题解我就写成深搜了
#include <bits/stdc++.h>
using namespace std;
const int N = 505;
queue<pair<int,int> > q;//队列,存待跳结果
int ans[N][N];//存步数
const int dx[8] = {-1,-2,-2,-1,1,2,2,1};
const int dy[8] = {2,1,-1,-2,2,1,-1,-2};//8个方向上的跳跃
int n,m;//长和宽
int x,y;//马的初始位置
int main()
{
memset(ans,-1,sizeof ans);
cin >> n >> m >> x >> y;
ans[x][y] = 0;//马站的位置
q.push({x,y});//初始位置入栈
while(!q.empty())
{
int xx = q.front().first;
int yy = q.front().second;//提出坐标
q.pop();//出队
for(int i = 0 ; i < 8 ; i++)
{
int pp = xx + dx[i];
int qq = yy + dy[i];//马可能跳到的位置
if(pp > 0 && pp <= n && qq > 0 && qq <= m && ans[pp][qq] == -1)//判断跳到的位置是否合法
{
ans[pp][qq] = ans[xx][yy] + 1;
q.push({pp,qq});
}
}
}
for(int i = 1 ; i <= n ; i++)
{
for(int j = 1 ; j <= m ; j++)
{
printf("%-5d",ans[i][j]);
}
cout << endl;
}
return 0;
}