欧拉计划005 Lattice paths

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值