思路:BFS
其实也就是对于走的方式进行修改就行了,这和上一个马的遍历是一样的。
只不过这里又多了一个走"田"字。
上代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include <iomanip>
#include<sstream>
#include<numeric>
#include<map>
#include<limits.h>
#include<set>
#define int long long
#define MAX 30
#define _for(i,a,b) for(int i=a;i<(b);i++)
#define ALL(x) x.begin(),x.end()
using namespace std;
typedef pair<int, int> PII;
int n, m;
int counts;
char maps[MAX][MAX];
int dist[MAX][MAX];
int x1, y, x2, y2;
queue<PII>q;
int dx[] = { 2,2,-2,-2,-1,-1,1,1,2,2,-2,-2 };
int dy[] = { 1,-1,-1,1,2,-2,2,-2,2,-2,2,-2 };
int bfs(int st1, int st2) {
memset(dist, -1, sizeof dist);
q.push({ st1,st2 });
dist[st1][st2] = 0;
while (!q.empty()) {
auto tmp = q.front();
q.pop();
for (int i = 0; i < 12; i++) {
int a = dx[i] + tmp.first;
int b = dy[i] + tmp.second;
if (a <= 0 || b <= 0||a>20||b>20)
continue;
if (dist[a][b] >= 0)
continue;
dist[a][b] = dist[tmp.first][tmp.second] + 1;
q.push({ a,b });
}
}
return dist[1][1];
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> x1 >> y;
cin >> x2 >> y2;
cout << bfs(x1, y) << endl;
cout << bfs(x2, y2) << endl;
return 0;
}