题目描述
有一个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
这题只需要搞清楚马的八种走法就可以了,用bfs很快就做出来了,注意最后的输出格式
#include <iostream>
#include <queue>
#include <algorithm>
#include <string.h>
#include <stdio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
struct node{
int x;
int y;
int step;
};
queue<node> q;
int n,m,x,y;
int map[500][500],vis[500][500];
bool ok(node u)
{
if(u.x>=1&&u.x<=n&&u.y>=1&&u.y<=m&&vis[u.x][u.y]!=1)
{
return true;
}else
{
return false;
}
}
void f(node v,node p)
{
if(ok(v))
{
v.step=p.step+1;
vis[v.x][v.y]=1;
map[v.x][v.y]=v.step;
q.push(v);
}
}
void bfs(int x,int y)
{
node p;
p.x=x,p.y=y,p.step=0;
map[x][y]=0;
vis[x][y]=1;
q.push(p);
while(!q.empty())
{
node p=q.front();
q.pop();
node v;
v.x=p.x-1;
v.y=p.y+2;
f(v,p);
v=p;
v.x=p.x+1;
v.y=p.y+2;
f(v,p);
v=p;
v.x=p.x-2;
v.y=p.y-1;
f(v,p);
v=p;
v.x=p.x-2;
v.y=p.y+1;
f(v,p);
v=p;
v.x=p.x+2;
v.y=p.y-1;
f(v,p);
v=p;
v.x=p.x+2;
v.y=p.y+1;
f(v,p);
v=p;
v.x=p.x-1;
v.y=p.y-2;
f(v,p);
v=p;
v.x=p.x+1;
v.y=p.y-2;
f(v,p);
}
}
int main(int argc, char *argv[]) {
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
map[i][j]=-1;
}
}
memset(vis,0,sizeof(vis));
cin>>x>>y;
bfs(x,y);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
//cout<<map[i][j]<<" ";
printf("%-5d",map[i][j]);
}
if(i!=n) cout<<endl;
}
return 0;
}