P1443 马的遍历
题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入格式
一行四个数据,棋盘的大小和马的坐标
输出格式
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
输入输出样例
输入 #1
3 3 1 1
输出 #1
0 3 2 3 -1 1 2 1 4
思路:bfs,每走一步判断当前点能到达哪些点,并记录步数
#include <iostream>
#include<queue>
#include<cstdio>
using namespace std;
int main()
{
int n, m, x, y;
scanf("%d%d%d%d", &n, &m, &x, &y);
int horse[450][450];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++)
horse[i][j] = -1;
}
horse[x][y] = 0;
queue<pair<int, int> >q;
q.push(make_pair(x, y));
while(!q.empty()){
int siz = q.size();
for(int i = 0; i < siz; i++){
pair<int, int>mypair = q.front();
q.pop();
int next[8][2] = {{-2, 1},{-2, -1}, {2, -1}, {2, 1}, {1, -2}, {1, 2},{-1, -2}, {-1, 2}};
for(int j = 0; j < 8; j++){
int dx = mypair.first + next[j][0];
int dy = mypair.second + next[j][1];
if(dx < 1 || dx > n || dy < 1 || dy > m){
continue;
}
if(horse[dx][dy] != -1)
continue;
else{
horse[dx][dy] = horse[mypair.first][mypair.second] + 1;
// pair<int,int>mp = {dx, dy};
q.push(make_pair(dx, dy));
}
}
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
printf("%-5d", horse[i][j]);
}
printf("\n");
}
return 0;
}