P1443 马的遍历(洛谷,BFS)

题目描述

有一个 n \times mn×m 的棋盘,在某个点 (x, y)(x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。

输入格式

输入只有一行四个整数,分别为 n, m, x, yn,m,x,y。

输出格式

一个 n \times mn×m 的矩阵,代表马到达某个点最少要走几步(左对齐,宽 55 格,不能到达则输出 -1−1)。

输入输出样例

输入 #1复制

3 3 1 1

输出 #1复制

0    3    2    
3    -1   1    
2    1    4    

说明/提示

数据规模与约定

对于全部的测试点,保证 1 \leq x \leq n \leq 4001≤x≤n≤400,1 \leq y \leq m \leq 4001≤y≤m≤400。

从开始点广度优先遍历,用数组a存储步数 比如从now这个节点遍历到next这个节点a[next.x][next.y]=a[now.x][now.y]+1

#include<iostream>
#include<cstring> 
#include<cstdio>
#include<queue>
using namespace std;
int dir[8][2]={
   
   {2,1},{2,-1},{1,2},{1,-2},{-2,1},{-2,-1},{-1,2},{-1,-2}};
bool vis[405][405]; 
struct Node{
	int x;
	int y;
}now,next;
int n,m,x1,y1;
int a[405][405]={-1};
void bfs(int x1,int y1,int step)
{
	a[x1][y1]=step;
	vis[x1][y1]=true;
	queue<Node>q;
	now.x=x1,now.y=y1;
	q.push(now);
	while(!q.empty())
	{
		now=q.front();
		q.pop();
		for(int i=0;i<8;i++)
		{
			next.x=now.x+dir[i][0];
			next.y=now.y+dir[i][1];
			if(!vis[next.x][next.y]&&next.x>=1&&next.y>=1&&next.x<=n&&next.y<=m)	//未标记过并且没出界 
			{	
				vis[next.x][next.y]=true;
				q.push(next);
				a[next.x][next.y]=a[now.x][now.y]+1;
			}
		}
	}
	
}
int main()
{
	memset(vis,false,sizeof(vis));//初始化为-1没遍历过就代表没走过 
	memset(a,-1,sizeof(a));
	cin>>n>>m>>x1>>y1;
	a[x1][y1]=0;
	bfs(x1,y1,0);		//从(1,1)点开始  这时候步数是0 
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			printf("%-5d",a[i][j]);
		}
		cout<<endl;
	}
}

Guess you like

Origin blog.csdn.net/qq_52245648/article/details/119767677