题目链接:https://cn.vjudge.net/problem/OpenJ_Bailian-4103
Description
有一个方格矩阵,矩阵边界在无穷远处。我们做如下假设:
a. 每走一步时,只能从当前方格移动一格,走到某个相邻的方格上;
b. 走过的格子立即塌陷无法再走第二次;
c. 只能向北、东、西三个方向走;
请问:如果允许在方格矩阵上走n步,共有多少种不同的方案。2种走法只要有一步不一样,即被认为是不同的方案。
Input
允许在方格上行走的步数n(n <= 20)
Output
计算出的方案数量
Sample Input
2Sample Output
7
AC代码
#include <iostream>
#include <cstring>
using namespace std;
bool book[51][51]; // 最多20步,所以20*2+1就够
int dfs(int x,int y,int n)
{
if(n == 0)
return 1;
int num=0;
int next[3][2] = {{0,1},{1,0},{0,-1}};
int tx,ty;
for(int i=0;i<3;i++) {
tx = x+next[i][0];
ty = y+next[i][1];
if(!book[tx][ty]) {
book[tx][ty] = true;
num += dfs(tx,ty,n-1);
book[tx][ty] = false;
}
}
return num;
}
int main()
{
int n;
cin >> n;
memset(book,false,sizeof book);
book[25][25]=true;
cout << dfs(25,25,n); //把起点设为(25,25),
}