跳到正文

题解

题解:P1443 马的遍历

zxcar999约 5 分钟
原文

这是 2026年1月2日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年1月1日
收录
2026年1月2日
更新
2026年11月19日
篇幅
约 5 分钟
题目
P1443

版本

  1. v2当前
  2. v1

P1443 马的遍历 题解

题目传送门

题目分析

这是一道典型的最短路径搜索题,深搜广搜都可以,本题解使用广度优先搜索。

解法

STL 的 queue 真的好用。
我们定义一个结构体, queue 与数组。

C++
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 广搜的模板。

C++
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 二维数组用于记录答案与打标记。

C++
int ans[1010][1010];
bool b[1010][1010];

融入广搜代码。

C++
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});
    }
  }
}

最后输出。

C++
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 代码。

C++
#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;
}

完结撒花。