题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入格式
一行四个数据,棋盘的大小和马的坐标
输出格式
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
输入
3 3 1 1
输出
0 3 2
3 -1 1
2 1 4
这道题如果用深度优先搜索(dfs)会超时的,因为每次你遍历的点不一定是最少步骤数,所以每个点你需要重复判断多遍。用广度优先搜索就可以了。
#include<bits/stdc++.h>
using namespace std;
int n,m,x,y;
int dx[8]={-2,-2,-1,-1,1,1,2,2};
int dy[8]={-1,1,-2,2,2,-2,1,-1};
int book[500][500],chess[500][500];
queue<int>q,q1;
void bfs(int x,int y)
{
q.push(x);
q1.push(y);
chess[x][y]=0;
book[x][y]=1;
while(!q.empty())
{
for(int i=0;i<8;i++)
{
int tx=q.front()+dx[i];
int ty=q1.front()+dy[i];
if(tx>0&&tx<=n&&ty>0&&ty<=m&&book[tx][ty]==0)
{
book[tx][ty]=1;
q.push(tx);
q1.push(ty);
chess[tx][ty]=chess[q.front()][q1.front()]+1;
}
}
q.pop();
q1.pop();
}
}
int main()
{
cin>>n>>m>>x>>y;
memset(chess,-1,sizeof(chess));
bfs(x,y);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
printf("%-5d",chess[i][j]);
}
cout<<endl;
}
return 0;
}