马的遍历(广度优先搜索)

题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步

输入格式
一行四个数据,棋盘的大小和马的坐标

输出格式
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)

输入 
3 3 1 1
输出 
0    3    2    
3    -1   1    
2    1    4    

这道题如果用深度优先搜索(dfs)会超时的,因为每次你遍历的点不一定是最少步骤数,所以每个点你需要重复判断多遍。用广度优先搜索就可以了。

#include<bits/stdc++.h>
using namespace std;
int n,m,x,y;
int dx[8]={-2,-2,-1,-1,1,1,2,2};
int dy[8]={-1,1,-2,2,2,-2,1,-1};
int book[500][500],chess[500][500];
queue<int>q,q1;


void bfs(int x,int y)
{
	q.push(x);
	q1.push(y);
	chess[x][y]=0;
	book[x][y]=1;
	while(!q.empty())
	{
		for(int i=0;i<8;i++)
		{
			int	tx=q.front()+dx[i];
			int ty=q1.front()+dy[i];
			if(tx>0&&tx<=n&&ty>0&&ty<=m&&book[tx][ty]==0)
			{	
				book[tx][ty]=1;
				q.push(tx);
				q1.push(ty);
				chess[tx][ty]=chess[q.front()][q1.front()]+1;
			}	
		}	
		q.pop();
		q1.pop();
	}		
}

int main()
{
	cin>>n>>m>>x>>y;
	memset(chess,-1,sizeof(chess));
	bfs(x,y);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			printf("%-5d",chess[i][j]);
		}
		cout<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值