POJ 2488 A Knight's Journey解题报告(回溯算法)

题目来源:POJ 2488 A Knight's Journey

http://acm.pku.edu.cn/JudgeOnline/problem?id=2488

 

解法类型:回溯算法

 

作者:刘亚宁

 

题目大意:给出一个棋盘的大小,判断马能否不重复的走过所有格,并记录下其中一种走法。

 

题目思路:经典回溯,特殊性不是很强。特殊点是需记录走法,方法是,如果走成功则记录该步的走法,否则不记录。

 

提交情况:无错误提交记录。

 

注意:代码中还有许多不精简之处,望各位指教改正。

 

源程序:

 

#include <iostream>

#include <string>

#include <cstdio>

 

using namespace std;

 

int map[30][30],c,r,num;

string ans;

 

int dfs(int i, int j)

{

                       if(map[i][j]) return 0;

                       num++;        

                       ans+=i;

                       ans+=j;

                       map[i][j]=1;

                       if(num==r*c) return 1;         

                       if(i-2>=1&&j-1>=1&&dfs(i-2,j-1)) return 1;

                       else if(i-2>=1&&j+1<=c&&dfs(i-2,j+1)) return 1;

                       else if(i-1>=1&&j-2>=1&&dfs(i-1,j-2)) return 1;

                       else if(i-1>=1&&j+2<=c&&dfs(i-1,j+2)) return 1;

                       else if(i+1<=r&&j-2>=1&&dfs(i+1,j-2)) return 1;

                       else if(i+1<=r&&j+2<=c&&dfs(i+1,j+2)) return 1;       

                       else if(i+2<=r&&j-1>=1&&dfs(i+2,j-1)) return 1;

                       else if(i+2<=r&&j+1<=c&&dfs(i+2,j+1)) return 1;

                       ans.resize(ans.size()-2);

                       map[i][j]=0;

                       num--;

                       return 0;

}

 

int main()

{

                       long caseNum,i;

                       cin>>caseNum;

                       for(i=1;i<=caseNum;i++)

                       {

                            cout<<"Scenario #"<<i<<":"<<endl;

                            num=0;

                            memset(map,0,sizeof(map));

                            ans="";

                            cin>>c>>r;

                            if(dfs(1,1))

                            {

                                     for(int j=0;j<ans.size();j++)

                                     {

                                               if(j%2) ans[j]+='0';

                                               else ans[j]+='A'-1;

                                     }

                                     cout<<ans<<endl<<endl;

                            }

                            else cout<<"impossible"<<endl<<endl;

                       }

                       return 0;

}

你可能感兴趣的:(poj)