😊😊 😊😊
不求点赞,只求耐心看完,指出您的疑惑和写的不好的地方,谢谢您。本人会及时更正感谢。希望看完后能帮助您理解算法的本质
😊😊 😊😊
马的遍历
题目描述
有一个 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 1≤x≤n≤400, 1 ≤ y ≤ m ≤ 400 1 \leq y \leq m \leq 400 1≤y≤m≤400。
小白到进阶各种解法:
一、暴搜:😊
思路:
- 从马的起点开始往8个方向进行搜索,等价于有8个分支。
- 当起点的八个方向都搜索返回后,即为递归的出口。
- 二维平面上的搜索,通常根据题意来确定偏移量,有时候是4个方向,有时候是8个方向。然后递归循环枚举这8个方向,进行搜索!
- 其实对于在二维平面上的搜索,主要的一点就是下一步是否越界的问题。若下一步越界,则返回。
- 本题还加了个分支: d i s t [ a ] [ b ] < = c + 1 dist[a][b] <= c+1 dist[a][b]<=c+1,其中 ( a , b ) (a,b) (a,b)为下一步要走的点,若下一步已经走过了,且之前走到 ( a , b ) (a,b) (a,b),的距离比当前走到 ( a , b ) (a, b) (a,b) 的路径更短则采无需往下走!
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 4e2 + 10;
int dist[N][N]; //从起点到点(i,j)的最短路径!
int n, m;
int dx[] = {-2, -2, -1, 1, 2, 2, 1, -1};
int dy[] = {-1, 1, 2, 2, 1, -1, -2, -2};
void dfs(int x, int y, int c)
{
dist[x][y] = c;
for (int i=0; i < 8; i ++)
{
int a = x + dx[i], b = y + dy[i];
if (a < 1 || a > n || b < 1 || b > m || dist[a][b] <= c + 1) continue;
dfs(a, b, c + 1);
}
}
int main()
{
memset (dist, 0x3f, sizeof(dist));
cin >> n >> m;
int x, y;
cin >> x >> y;
dfs (x, y, 0);
for (int i=1; i <= n; i ++)
{
for (int j=1; j <= m; j ++)
{
if (dist[i][j] != 0x3f3f3f3f) cout << dist[i][j] << " ";
else cout << -1 << " ";
}
puts("");
}
return 0;
}
二、广度优先搜索:BFS😊
思路:
其实bfs就是直接套模板,这里讲解下bfs的模板即可:
- 广度优先搜索,会优先考虑每种状态和初始状态的距离,形象点说,与初始状态越接近的情况就会优先考虑。再具体一点来说,每个时刻(阶段),要做的事情就是从上个时刻(阶段)每个状态扩展出来的新的状态。
- 广度优先搜索是使用队列实现的,先将初始状态加入到空的队列中,然后每次取出队首,找出队首所能转移到的状态,再将其压入队列中,如此反复,直到队列为空时停止,这样就能保证一个状态在被访问的时候一定是采用的最短路径。
其核心伪代码如下:
Q.push(初始状态);
while (队列不为空)
{
取出队首;
弹出队首。
for (枚举所有可扩展的状态)即找到当前队首的所有可达的状态。
if(该状态是合法的) 通常需要满足:未访问过,没有越界,是否在队内等条件的判断;
Q.push(最后将其入队);同时可能需要维护其他的信息。
}
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#define x first
#define y second
using namespace std;
const int N = 400 + 10;
int n, m;
int x, y;
int dx[] = {-2, -2, -1, 1, 2, 2, 1, -1};
int dy[] = {-1, 1, 2, 2, 1, -1, -2, -2};
typedef pair<int, int> PII;
int dist[N][N];
void bfs(int x, int y)
{
memset (dist, -1, sizeof (dist));
queue<PII>q;
q.push({x, y});
dist[x][y] = 0;
while (q.size())
{
auto t = q.front();
q.pop();
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 || dist[a][b] != -1)
continue;
q.push({a, b});
dist[a][b] = dist[t.x][t.y] + 1;
}
}
for (int i=1; i <= n; i ++)
{
for (int j=1; j <= m; j ++)
printf ("%-5d", dist[i][j]);
puts("");
}
}
int main()
{
cin >> n >> m >> x >> y;
bfs (x, y);
return 0;
}
三、本题考察算法:😊
代码: