Problem
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
解题思路
这题我的第一想法就是找规律,然后没找好,就用搜索写了第一个代码,然后我发现跑出来的太耗时了,17*17的方格都要跑好久的,所以我觉得应该是规律的问题。然后我就根据第一个代码进行修改,把(0,0)到任意一个点的情况输出来,找到了关键所在。
想到达(tx,ty)这一点,可以先到达(tx-1,ty)和(tx,ty-1)这两点,然后总结过就是两者之和了。
程序代码
这里是第一次写的,搜索的写法,15*15的方格就需要24.63s.
#include <stdio.h>
#include <string.h>
int map[25][25];
int book[25][25];
int next[2][2]={{1,0},{0,1}};
long long flag,n;
void dfs(int x,int y){
int k,tx,ty;
if(x==n&&y==n){
flag++;
}
for(k=0;k<2;k++){
tx=x+next[k][0];
ty=y+next[k][1];
book[tx][ty]++;
if(tx>n||ty>n)
continue;
dfs(tx,ty);
}
return ;
}
int main(){
int i,j;
while(scanf("%lld",&n)!=EOF){
flag=0;
memset(map,0,sizeof(map));
memset(book,0,sizeof(book));
dfs(0,0);
for(i=0;i<=n;i++){
for(j=0;j<=n;j++)
printf("%6d ",book[i][j]);
printf("\n");
}
printf("number=%lld\n",flag);
}
return 0;
}
/*
14*14 number is 40116600!
15*15 number is 155117520!
16*16 number is 601080390!
17*17 number is 2333606220!
*/
这是求得答案的代码,比较简单
#include <stdio.h>
#include <string.h>
#define ll long long
int main()
{
int i,j;
ll p[25][25];
memset(p,0,sizeof(p));
for(i=1;i<=20;i++){
p[i][0]=1;
for(j=1;j<=i;j++){
if(i==j)
p[i][j]=2*p[i][j-1];
else
p[i][j]=p[i][j-1]+p[i-1][j];
}
}
for(i=0;i<=20;i++){
for(j=0;j<=i;j++)
printf("%lld ",p[i][j]);
printf("\n");
}
return 0;
}