题目:
Description
在一个4×5的棋盘上,输入马的起始位置坐标(纵,横)位置,求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走“日”字)。
Input
输入只有一行,包括两个整数,既马的起始位置坐标x和y值,并且,这个坐标一定在4×5的小棋盘上,即 0<x<=4, 0<y<="5.
Output
一个整数,为能返回到初始位置的所有不同走法的总数。
Sample Input
Original | Transformed |
2 2 1 1 1 3
Sample Output
Original | Transformed |
4596 1508 4772
分析:DFS
代码:
#include<iostream> #include<cstdio> #include<queue> #include<string> #include<cstring> using namespace std; int next1[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}}; int book[10][10],sum; int a,b; int dfs(int x,int y) { int tx,ty; for(int k=0;k<8;k++) { tx=x+next1[k][0]; ty=y+next1[k][1]; if(tx==a&&ty==b) sum++; if(tx<1||tx>4||ty<1||ty>5) continue; if(book[tx][ty]==0) { book[tx][ty]=1; dfs(tx,ty); book[tx][ty]=0; } } return sum; } int main() { while(~scanf("%d%d",&a,&b)) { sum=0; memset(book,0,sizeof(book)); book[a][b]=1; printf("%d ",dfs(a,b)); } return 0; }