题目描述
有一个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 <iomanip>
#include <cstring>
using namespace std;
struct note
{
int x;
int y;
};
int next_step[][2] = { {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2} };
int map[400][400];
int book[400][400];
note que[160000];
int main()
{
memset(map, -1, sizeof(map));
//注意这个函数的使用方法,他只能填充0和-1,应为这个函数是将数字对应的二进制值填入数组,只有这两个数的二进制数每一位都一样
int head, tail, n, m, startx, starty, tx, ty;
head = tail = 0;
cin >> n >> m >> startx >> starty;
que[tail].x = startx - 1; que[tail].y = starty - 1;
tail++;
book[startx - 1][starty - 1] = 1;
map[startx - 1][starty - 1] = 0;//直接记录步数(实际上book数组不光可以用于判断,还可以用于记录图的每个位置对应的数值)map也是一样
while (head < tail)
{
for (int i = 0; i < 8; i++)
{
tx = que[head].x + next_step[i][0];
ty = que[head].y + next_step[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < m && book[tx][ty] == 0)
{
book[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
map[tx][ty] = map[que[head].x][que[head].y] + 1;
tail++;
}
}
head++;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cout << setw(5) << left << map[i][j];
cout << endl;
}
return 0;
}
在清楚了这道提的解法后大家可以再加强一下哦~
相似的题目P1141 01迷宫——bfs解法