BFS 马的遍历————洛谷p1443

马的遍历

题目描述

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

输入格式

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

输出格式

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

样例 #1

样例输入 #1

3 3 1 1

样例输出 #1

0    3    2    
3    -1   1    
2    1    4

提示

数据规模与约定

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

##问题分析
常规的bfs题,每次入队八个方向,并标记入队时的层数,该层数即为马跳过的步数,越早跳到,所花费的步数就越少

#include<iostream>
#include <iomanip>
#include<cstring>
#include<queue>
using namespace std;
int n, m, x, y;
bool flag[450][450];//判断是否走过
int step[450][450] ; //记录步数
int dir[8][8] = { {1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1} }; //八个方向
queue<pair<int, int> >que; //这两个连续的>>最好还是加个空格,有的系统里会报错
void bfs(int x, int y) {
	step[x][y] = 0;
	flag[x][y] = true;
	que.push(make_pair(x, y));
	while (!que.empty()) {
		pair<int, int>t = que.front();
		que.pop();
		//flag[t.first][t.second] = true; //一开始把标记写在这里,没注意马可能会往回跳,所以应该在入队时就标记
		for (int i = 0; i < 8; i++) {
			int nx = t.first + dir[i][0], ny = t.second + dir[i][1];
			if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && !flag[nx][ny]) {
				que.push(make_pair(nx, ny));
				flag[nx][ny] = true; //标记
				step[nx][ny] = step[t.first][t.second] + 1; //记录步数
			}
		}
	}
}

int main() {
	cin >> n >> m >> x >> y;
	memset(flag, false, sizeof(flag));
	memset(step, -1, sizeof(step)); //初始化为-1
	bfs(x, y);
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << left << setw(5) << step[i][j]; //注意输出格式
		}
		cout << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值