题目:原题
有一个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的思想来求解
代码1 用数组模拟队列
#include<bits/stdc++.h>
using namespace std;
int a[401][401];//记录到达每一个点的步数
bool visit[401][401];//记录当前点是否已经走过
int dx[4]={1,-1,2,-2};//马行走的策略
int dy[4]={1,-1,2,-2};
struct node{
int x,y;
}q[160110],node,top;//q是用数组模拟的队列
int n,m;
void bfs(int x,int y){
//a[x][y]=step;
node.x=x;
node.y=y;
visit[x][y]=false;
int front=0,rear=0;
q[rear++]=node;//node入队
while(front!=rear){
top=q[front++];
for(int i=0;i<4;i++)
for(int j=0;j<4;j++){
if(abs(dx[i])!=abs(dy[j])){
int newx=top.x+dx[i];
int newy=top.y+dy[j];
if(newx<1 ||newx>n || newy<1 ||newy>m) continue;
if(visit[newx][newy]){
visit[newx][newy]=false;
node.x=newx;
node.y=newy;
q[rear++]=node;
a[newx][newy]=a[top.x][top.y]+1;
}
}
}
}
}
int main(){
memset(visit,true,sizeof(visit));//如果不初始化的话,b的初始值应该是false的
memset(a,-1,sizeof(a));//这个也非常必要,默认是-1即无法到达
int x,y;
cin>>n>>m>>x>>y;
a[x][y]=0;//到达起点是0步
bfs(x,y) ;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++)
printf("%-5d",a[i][j]);
cout<<endl;
}
return 0;
}
代码2 用queue
(上面用数组的解法也是参考这个,参考)
#include<bits/stdc++.h>
using namespace std;
struct xy{
int x;
int y;
}node,Top;
int dx[4]={1,-1,2,-2};
int dy[4]={1,-1,2,-2};//一共有16个方向,两两组合
int a[401][401];
bool b[401][401];
int n,m;
void bfs(int x,int y,int step){
a[x][y]=step;
b[x][y]=false;
queue<xy> Q;
node.x=x;
node.y=y;
Q.push(node);
while(!Q.empty()){
Top=Q.front();
Q.pop();
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(abs(dx[i])!=abs(dy[j])){
int NewX=Top.x+dx[i];
int NewY=Top.y+dy[j];
if(NewX<1 || NewX>n || NewY<1 || NewY>m) continue;
if(b[NewX][NewY]){
node.x=NewX;
node.y=NewY;
Q.push(node);
b[NewX][NewY]=false;
a[NewX][NewY]=a[Top.x][Top.y]+1;//这里怎么理解?
}
}
}
}
}
int main(){
memset(b,true,sizeof(b));
memset(a,-1,sizeof(a));
int x,y;
cin>>n>>m>>x>>y;
bfs(x,y,0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
printf("%-5d",a[i][j]);
cout<<endl;
}
return 0;
}