基本思想:
有一个大坑,就是字典序的问题;
还有一个就是代码简洁度的问题;
关键点:
无;
#include<iostream>
#include<vector>
#include<string>
using namespace std;
const int maxn = 30;
int p, q;
bool vis[maxn][maxn];
int direction[8][2] = {
{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}
};
bool dfs(int x, int y, int step, string ans) {
if (step == p * q) {
cout << ans << endl << endl;
return true;
}
for (int i = 0; i < 8; i++) {
int nx = x + direction[i][0];
int ny = y + direction[i][1];
char col = ny + ‘A‘;
char row = nx + ‘1‘;
if (nx < 0 || nx >= p || ny<0 || ny>=q || vis[nx][ny]) {
continue;
}
vis[nx][ny] = true;
if (dfs(nx, ny, step + 1, ans + col + row))
return true;
vis[nx][ny] = false;
}
return false;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> p >> q;
fill(vis[0], vis[0] + maxn, false);
cout << "Scenario #" << i + 1 << ":" << endl;
vis[0][0] = true;
if (!dfs(0, 0, 1, "A1"))
cout << "impossible" << endl << endl;
}
return 0;
}
Poj机试 A Knight's Journey *BFS,存在问题
原文:https://www.cnblogs.com/songlinxuan/p/12445026.html