题解:P1443 马的遍历
P1443 马的遍历 题解
题目传送门
题目分析
这是一道典型的最短路径搜索题,深搜广搜都可以,本题解使用广度优先搜索。
解法
STL 的 queue 真的好用。 我们定义一个结构体,queue 与数组。
struct node{
int x,y,cnt;
};
int p[10][2]={{2,1},{1,2},{-2,-1},{-1,-2},{2,-1},{1,-2},{-2,1},{-1,2}};//方便移动马的位置
queue<node> q;
按照 queue 广搜的模板。
int n,m,xr,yr;
cin>>n>>m>>xr>>yr;
q.push({xr,yr,0});//起点
while(!q.empty()){
int xx=q.front().x;
int yy=q.front().y;
int c=q.front().cnt;//读取队首
q.pop();//删除队首
for(int i=0;i<8;i++){//8个走法
int xxx=xx+p[i][0];
int yyy=yy+p[i][1];
if(xxx>0&&xxx<=n&&yyy>0&&yyy<=m){//防止越界
q.push({xxx,yyy,c+1});//加入新的一步
}
}
}
然后定义 ans 与 b 二维数组用于记录答案与打标记。
int ans[1010][1010];
bool b[1010][1010];
融入广搜代码。
memset(ans,0x3f3f3f3f,sizeof(ans));//防止无法到达输出0
int n,m,xr,yr;
cin>>n>>m>>xr>>yr;
q.push({xr,yr,0});
while(!q.empty()){
int xx=q.front().x;
int yy=q.front().y;
int c=q.front().cnt;
q.pop();
ans[xx][yy]=min(ans[xx][yy],c);
for(int i=0;i<8;i++){
int xxx=xx+p[i][0];
int yyy=yy+p[i][1];
if(xxx>0&&xxx<=n&&yyy>0&&yyy<=m&&b[xxx][yyy]==0){
b[xxx][yyy]=1;
q.push({xxx,yyy,c+1});
}
}
}
最后输出。
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(ans[i][j]==0x3f3f3f3f){
cout<<-1<<" ";
}else{
cout<<ans[i][j]<<" ";
}
}
cout<<endl;
}
AC 代码。
#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
struct node{
int x,y,cnt;
};
int p[10][2]={{2,1},{1,2},{-2,-1},{-1,-2},{2,-1},{1,-2},{-2,1},{-1,2}};
int ans[1010][1010];
bool b[1010][1010];
queue<node> q;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(ans,0x3f3f3f3f,sizeof(ans));
int n,m,xr,yr;
cin>>n>>m>>xr>>yr;
q.push({xr,yr,0});
while(!q.empty()){
int xx=q.front().x;
int yy=q.front().y;
int c=q.front().cnt;
q.pop();
//cout<<xx<<" "<<yy<<" "<<c<<endl;
ans[xx][yy]=min(ans[xx][yy],c);
for(int i=0;i<8;i++){
int xxx=xx+p[i][0];
int yyy=yy+p[i][1];
if(xxx>0&&xxx<=n&&yyy>0&&yyy<=m&&b[xxx][yyy]==0){
b[xxx][yyy]=1;
q.push({xxx,yyy,c+1});
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(ans[i][j]==0x3f3f3f3f){
cout<<-1<<" ";
}else{
cout<<ans[i][j]<<" ";
}
}
cout<<endl;
}
return 0;
}
完结撒花。