问题描述
输入
输入n和m
输出
输出最少的步数
样例输入
6 5
样例输出
3
题目解读
这道题可谓是BFS的经典习题。
我们设计两个队列Q,step,分别用来储存当前的状态、当前状态所对应的步数
每次读取状态的时候分别取两个队列的队首,伸展向四个日字格即可
code
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0 , f = 1; char ch = getchar();
for ( ; !isdigit(ch) ; ch = getchar()) if (ch == '-') f = -1;
for ( ; isdigit(ch) ; ch = getchar()) x = x * 10 + ch - '0';
return x * f;
}
const int dirx[] = {1 , 1 , 2 , 2};
const int diry[] = {2 , -2 , 1 , -1};
const int maxn = 51;
queue <pair <int , int> > Q;
queue <int> step;
int vis[maxn][maxn];
int n , m , x , y;
int main() {
n = read() , m = read();
Q.push(make_pair(1 , 1));
step.push(0);
vis[1][1] = true;
while (Q.size()) {
int nowx = Q.front().first , nowy = Q.front().second , nowStep = step.front();
Q.pop() , step.pop();
if (nowx == n && nowy == m) {
cout << nowStep << endl;
exit(0);
}
for (int i = 0 ; i < 4 ; i ++) {
int nextx = nowx + dirx[i] , nexty = nowy + diry[i];
if (nextx <= 0 || nexty <= 0 || nextx > n || nexty > m) {
continue;
}
else if (vis[nextx][nexty]) {
continue;
}
else {
Q.push(make_pair(nextx , nexty));
step.push(nowStep + 1);
vis[nextx][nexty] = true;
}
}
}
puts("No solution!");
}