1. 程式人生 > 其它 >【洛谷】P1443 馬的遍歷

【洛谷】P1443 馬的遍歷

題目描述

有一個 n \times mn×m 的棋盤,在某個點 (x, y)(x,y) 上有一個馬,要求你計算出馬到達棋盤上任意一個點最少要走幾步。

輸入格式

輸入只有一行四個整數,分別為 n, m, x, yn,m,x,y。

輸出格式

一個 n \times mn×m 的矩陣,代表馬到達某個點最少要走幾步(左對齊,寬 55 格,不能到達則輸出 -11)。

輸入輸出樣例

 

bfs板子

ac程式碼

#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
int meme[500][500];
int n,m;
struct yuu{
	int x,y,step;
};
queue<struct yuu> op;
void bfs(int x,int y,int step)
{
	if(x>=1&&x<=n&&y>=1&&y<=m&&meme[x][y]==-1)
	{
		struct yuu inp;
	    inp.step=step;inp.x=x;inp.y=y;
	    op.push(inp);
		meme[x][y]=step;	
	}
}
int main()
{
	for(int i=0;i<500;i++)
	   for(int j=0;j<500;j++)
	        meme[i][j]=-1;
	int x,y;
	cin>>n>>m>>x>>y;
	struct yuu inp;
	inp.step=0;inp.x=x;inp.y=y;
	meme[x][y]=0;
	op.push(inp);
	while(!op.empty())
	{
		inp=op.front();
		bfs(inp.x-1,inp.y-2,inp.step+1);
		bfs(inp.x-2,inp.y-1,inp.step+1);
		bfs(inp.x+1,inp.y+2,inp.step+1);
		bfs(inp.x+2,inp.y+1,inp.step+1);
		bfs(inp.x-1,inp.y+2,inp.step+1);
		bfs(inp.x-2,inp.y+1,inp.step+1);
		bfs(inp.x+1,inp.y-2,inp.step+1);
		bfs(inp.x+2,inp.y-1,inp.step+1);
		op.pop();
	}
	for(int i=1;i<=n;i++)
	{
	    for(int j=1;j<=m;j++)
	    printf("%-5d",meme[i][j]);
	    cout<<endl;
	}
	return 0;
}



累了毀滅吧