洛谷P1443 马的遍历(bfs) 题解

题目来源:

点击打开链接

题目描述:

题目描述

有一个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 <cstring>
#include <iomanip>
#define maxn 405
using namespace std;
struct newt{
	int x,y,time;
}dian;
bool jl[maxn][maxn];
int tu[maxn][maxn];
int n,m;
queue<newt>q;
int dir[8][2]={{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};
bool pd(newt a)
{
	if(a.x>=1&&a.x<=n&&a.y>=1&&a.y<=m&&!jl[a.x][a.y])return 1;
	else return 0;
}
int main()
{
	cin>>n>>m;
	int a,b;
	cin>>a>>b;
	memset(jl,0,sizeof(jl));
	memset(tu,-1,sizeof(tu));
    dian.x=a;dian.y=b;
    dian.time=0;
    tu[a][b]=0;
    jl[a][b]=1;
    q.push(dian);
    while(!q.empty())
    {
    	newt now=q.front();
    	q.pop();
    	for(int i=0;i<8;i++)
    	{
    		newt nod;
    		nod.x=now.x+dir[i][0];
    		nod.y=now.y+dir[i][1];
    		nod.time=now.time+1;
    		if(pd(nod)){
    			q.push(nod);
    			tu[nod.x][nod.y]=nod.time;
    			jl[nod.x][nod.y]=1;
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		cout<<left<<setw(5)<<tu[i][j];
		cout<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40400202/article/details/80959542