Description
在一个4*5的棋盘上,输入马的起始位置坐标(纵、横),求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走“日”字)。
Input
多个测试数据。
每组2个数字
Output
输出不同走法的总数。
Sample Input
2 2
Sample Output
4596
Source
/*HORSE*/
#include <iostream>
#include <cstring>
using namespace std;
// (n,m)为初始坐标,res为走法的总数,dir为8中不同走法坐标变化值
int n,m,res,dir[2][8]={{-1,-1,-2,-2,2,2,1,1},{-2,2,1,-1,1,-1,2,-2}};
int chess[5][6]; // 记录棋盘的状态
void FindWay(int p1, int p2)
{
int x,y;
for(int i=0;i<8;i++)
{
x=p1+dir[0][i];
y=p2+dir[1][i];
if(chess[x][y]==0 && x>=1 && x<=4 && y>=1 && y<=5)
{
chess[x][y]=1;
FindWay(x,y);
chess[x][y]=0;
}
else if(x==n && y==m)
{
++res;
}
}
}
int main()
{
while(cin>>n>>m)
{
if(n>=1 && m>=1 && n<=4 && m<=5)
{
res=0;
memset(chess,0,sizeof(chess));
chess[n][m]=1;
FindWay(n,m);
cout<<res<<endl;
}
else cout<<"ERROR"<<endl;
}
return 0;
}
回溯法的使用.