题目描述:The knight is getting bored of seeing the same black and white squares again and again and has decided to make a journey
around the world. Whenever a knight moves, it is two squares in one direction and one square perpendicular to this. The world of a knight is the chessboard he is living on. Our knight lives on a chessboard that has a smaller area than a regular 8 * 8 board, but it is still rectangular. Can you help this adventurous knight to make travel plans?
解题思路:DFS
做题总结:
DFS函数的返回值,习惯上用bool会比较好一些
很容易出现超时现象
- 数值转化为string类型
- 记录武士已经走过的路径
AC代码:
// 本代码在poj上,G++通过,GCC、C++上编译失败
#include <iostream>
#include <cstring> // memset函数
using namespace std;
const int MAXN = 30 ;
int p,q,scenario;
bool vis[MAXN][MAXN]; // 标记矩阵
int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}}; // 下一步扩展的所有可能方向
bool check(int row, int col) {
if(row<1||row>p||col<1||col>q)
return false;
if(vis[row][col])
return false;
return true;
}
bool DFS(int row, int col, int num, string res) {
if(num==p*q) {
cout<<"Scenario #"<<scenario<<":"<<endl<<res<<endl<<endl;
return true;
}
for(int i=0; i<8; i++) {
int r = row + dir[i][0];
int c = col + dir[i][1];
char nr = r-1+'1';
char nc = c-1+'A';
if(!check(r,c)) continue;
vis[r][c]=true;
if(DFS(r,c,num+1,res+nc+nr)) return true;
vis[r][c]=false; // 这个步骤不要忘记
}
return false;
}
int main() {
int n;
cin>>n;
for(scenario=1; scenario<=n; scenario++) {
cin>>p>>q;
memset(vis,false,sizeof(vis)); // 初始化数组
vis[1][1]=true;
if(!DFS(1,1,1,"A1")) {
cout<<"Scenario #"<<scenario<<":"<<endl<<"impossible"<<endl<<endl;
}
}
return 0;
}
超时代码:
#include <iostream>
#include <cstring> // memset函数
#include <sstream> // 用于int转为string类型
using namespace std;
const int MAXN = 26 + 1 ;
int p,q,scenario;
bool vis[MAXN][MAXN]; // 标记矩阵
int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}}; // 下一步扩展的所有可能方向
int flag=0; // 用于判断路径是否已找出
string path[MAXN*MAXN]; // 记录当前走过的路径
string rowTran(int row) {
stringstream ss;
ss<<row;
return ss.str();
}
string colTran(int col) {
stringstream ss;
ss<<((char)('A'+col-1));
return ss.str();
}
bool check(int row, int col) {
if(row<1||row>p||col<1||col>q)
return false;
if(vis[row][col])
return false;
return true;
}
void DFS(int row, int col, int num) {
if(flag==1)
return;
vis[row][col] = true;
path[num] = colTran(col) + rowTran(row);
if(num==p*q) {
cout<<"Scenario #"<<scenario<<":"<<endl;
for(int i=1;i<=num;i++){
cout<<path[i];
}
cout<<endl<<endl;
flag=1;
return;
}
for(int i=0; i<8; i++) {
int r = row + dir[i][0];
int c = col + dir[i][1];
if(check(r,c))
DFS(r,c,num+1);
}
vis[row][col] = false;
}
int main() {
int n;
cin>>n;
for(scenario=1; scenario<=n; scenario++) {
cin>>p>>q;
memset(vis,false,sizeof(vis));
flag=0;
DFS(1,1,1);
if(flag==0) {
cout<<"Scenario #"<<scenario<<":"<<endl<<"impossible"<<endl<<endl;
}
}
return 0;
}