Files
Data-Structure/Algorithm/DS-Related/Graph/DFS/UVa1600Knight-Move betteruseBSF.cpp
2025-08-31 10:21:06 +08:00

33 lines
773 B
C++

#include <iostream>
using namespace std;
//abÊÇÖÕµã
int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
int step[9][9];
void dfs(int _a, int _b, int _n, int _m){
if(_n > 8 || _n < 1 || _m < 1 || _m > 8) return;
if(_n == _a && _m == _b) return;
for(int i = 0; i < 8; i++){
int nx = _n + dx[i];
int ny = _m + dy[i];
if (nx >= 1 && nx <= 8 && ny >= 1 && ny <= 8) {
int stepnew = step[_n][_m] + 1;
if (step[nx][ny] == 0 || stepnew < step[nx][ny]) {
step[nx][ny] = stepnew;
dfs(_a, _b, nx, ny);
}
}
}
}
int main(){
int a, b, n, m;
cin >> n >> m >> a >> b;
step[n][m] = 0;
dfs(a, b, n, m);
cout << step[a][b] << endl;
return 0;
}