GDUT-专题学习1 C-马的遍历

                                                        C-马的遍历

题目

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

输入格式

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

输出格式

        一个 n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出−1)。

Sample Input:

3 3 1 1

Sample Output:

0    3    2    
3    -1   1    
2    1    4    

思路

        主要思路是模拟马的走法,即马走日(一共有8种走法),用bfs考虑8个方向套模板就行。

代码

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=110;
int px[]={-2,-1,-2,-1,2,1,2,1};//模拟8种走法
int py[]={-1,-2,1,2,-1,-2,1,2};
struct node{
	int x,y,step;
}xy,top;
queue<node>q; 
int ans[410][410];
bool flag[410][410];
int n,m,x0,y0;
void bfs(int x,int y,int step){
	ans[x][y]=step;
	flag[x][y]=false;
	xy.x=x;
	xy.y=y;
	q.push(xy);
	while(!q.empty()){
		top=q.front();
		q.pop();
		for(int i=0;i<8;i++){
			int tx=top.x+px[i];
			int ty=top.y+py[i];
			if(tx>0&&tx<=n&&ty>0&&ty<=m){
				if(flag[tx][ty]){
					xy.x=tx;
					xy.y=ty;
					q.push(xy);//入队
					ans[tx][ty]=ans[top.x][top.y]+1;//更新答案
					flag[tx][ty]=false;
				}
			}
		}
	}
}
int main(){
	cin>>n>>m>>x0>>y0;
	memset(ans,-1,sizeof(ans));
	memset(flag,true,sizeof(flag)); 
	bfs(x0,y0,0);
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cout<<ans[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值