踩方格 2020/12/1
首先我想到的是DFS方法,并写出了代码如下:
#include<iostream>
using namespace std;
//踩方格
int run(int x, int y, int flag, int a[25][45], int step)
{
if (step == 0)
{
return 1;
}
if (flag == -1)//向西
{
if (a[x][y - 1] == 1)
{
step--;
a[x][y - 1] = 0;
return run(x, y - 1, -1, a, step) + run(x, y - 1, 2, a, step);//因为刚从东往西走,所以下一步不能往东
}
else
{
return 0;
}
}
else if (flag == 1)//向东
{
if (a[x][y + 1] == 1)
{
step--;
a[x][y + 1] = 0;
return run(x, y + 1, 1, a, step) + run(x, y + 1, 2, a, step);//没有向西
}
else
{
return 0;
}
}
else if (flag == 2)//向北
{
if (a[x - 1][y] == 1)
{
step--;
a[x - 1][y] = 0;
return run(x - 1, y, -1, a, step) + run(x - 1, y, 1, a, step) + run(x - 1, y, 2, a, step);//继续向北向东向西都可以
}
else
{
return 0;
}
}
else if (flag == 0)
{
return run(x , y, -1, a, step) + run(x , y, 1, a, step) + run(x , y, 2, a, step);
}
}
int main()
{
int n;//允许走的步数
cin >> n;
int a[25][45];
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 45; j++)
{
a[i][j] = 1;
}
}
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 45; j++)
{
cout << a[i][j] << ' ';
}
cout << '\n';
}
int x = 21, y = 22;//初始位置
a[x][y] = 0;
cout << run(x,y,0,a,n);
}
然后很显然的发现答案是错误的,把二位数组作为参数传递过去,修改二维数组的话,下次用就不是初始的值了。。。。
就很头秃
继续看想到上课的动态规划,发现这不就是动态规划的题吗??!
然后想破了头也没想出递推公式
开始百度
递推公式为f(n)=f(n-1)*2+f(n-1)
也不知道为啥
标程如下:
//#include<bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int a[25];
a[0] = 0;
a[1] = 3;
a[2] = 7;
for (int i = 3; i <= n; i++)
{
a[i] = a[i - 1] * 2 + a[i - 2];
}
cout << a[n] << endl;
}
return 0;
}