前言
1.bfs能解决的两类问题
a.迷宫内自起点出发是否存在路径能抵达终点
b.自一点到另一点的最短路径
2.用队列的特性实现bfs(本人究极菜,拿数组模拟的队列)
题目描述
有一个 n×m 的棋盘,在某个点(x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
输入格式
输入只有一行四个整数,分别为 n,m,x,y。
输出格式
一个n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 −1)。
输入输出样例
输入
3 3 1 1
输出
0 3 2 3 -1 1 2 1 4
说明/提示
数据规模与约定
对于全部的测试点,保证 1≤x≤n≤400,1≤y≤m≤400。
题目分析
bfs的入门题,唯一要注意的是将答案数组初始化为-1以便于接下来的操作;
代码样例
#include <stdio.h>
#include <string.h>
const int N = 410;
typedef struct queue {
int x, y;
}que;
int n, m, x, y;
que q[N * N]; //存坐标的数组队列
int dist[N][N]; //答案数组
int dx[] = {2, 2, 1, 1, -1, -1, -2, -2};
int dy[] = {1, -1, 2, -2, 2, -2, 1, -1};
void bfs(int x, int y) {
memset(dist, -1, sizeof dist); //初始化为-1
q[0] = {x, y};
dist[x][y] = 0;
int hh = 0, tt = 0; //头尾指针
while(hh <= tt) {
que t = q[hh++]; //出队且头指针后移
for(int i = 0; i < 8; i++) { //马的行进方向
int a = t.x + dx[i], b = t.y + dy[i];
if(a < 1 || a > n || b < 1 || b > m) continue;
if(dist[a][b] >= 0) continue;
dist[a][b] = dist[t.x][t.y] + 1; //下一点权值加一
q[++tt] = {a, b};; //尾指针后移并入队
}
}
}
int main() {
scanf("%d %d %d %d", &n, &m, &x, &y);
bfs(x, y);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
printf("%-5d", dist[i][j]);
}
printf("\n");
}
return 0;
}