标签:搜索、广度优先搜索,BFS、队列
【题解】
一般的,求解的个数用深搜,求最优解用广搜。这题很明显,求马到达某个点最少要走几步,所以用广度优先搜索。
思路很简单,马能走八个方向,在搜索时逐一走一遍,满足条件就进队,再记录步数。
【代码】
#include <iostream>
#include <queue>
using namespace std;
int n, m, x, y, step; // step是步数
// 马能走的八个方向
int dir[8][2] = { {-1,-2}, {1,-2}, {-2,-1}, {2,-1}, {-2,1}, {2,1}, {-1,2}, {1,2} };
int loc[405][405]; // 记录到达该点所需步数
struct nodes{
int x, y;
}node, top;
queue<nodes> q;
void bfs(){
if (q.empty()) return; // 搜索结束条件,队列为空
top = q.front();
q.pop();
// 下面的for是从当前top位置开始走,所以新的步数是(top的步数+1)
step = loc[top.x][top.y] + 1;
for (int i = 0; i < 8; i++) { // 马走的八个方向
int dx = top.x + dir[i][0];
int dy = top.y + dir[i][1];
if (dx<1 || dy<1 || dx>n || dy>m || loc[dx][dy]) continue;
node.x = dx;
node.y = dy;
q.push(node);
loc[dx][dy] = step; // 置步数
}
bfs();
}
int main(){
scanf("%d%d%d%d", &n, &m, &x, &y);
// 先把起点进队,从起点开始搜索
node.x = x;
node.y = y;
q.push(node);
bfs();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i == x && j == y) // 起点
printf("%-5d", 0);
else if (loc[i][j] == 0) // 不能到达
printf("%-5d", -1);
else
printf("%-5d", loc[i][j]);
}
printf("\n");
}
return 0;
}