您的位置:首页 > 其它

projecteuler---->problem=15----Lattice paths

2014-06-03 16:43 465 查看
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?

翻译:

从一个2×2的方格的左上角开始,共有6条路径可达到右下角(不能后退)
请问,假如把上述方格的规模改成20×20,共有多少条路径呢

解析:从做PE题以来,这是第一次在一道题上卡了好一会,一开始想到的是深搜,不过没看到只能往右边和下边走,结果递归溢出。改了之后,还是跑不出结果

/*
 * main.c
 *
 *  Created on: Jun 3, 2014
 *      
 */

#include <stdio.h>

int posX[2]={ 0, 1};
int posY[2]={ 1, 0};
unsigned long count=0;
int max=20;

void f(int x, int y){
    int i, nx, ny;
	if (x==max && y==max){
    	    count++;
    	    return ;
    }
    for (i=0; i < 2; i++){
    	    nx=x+posX[i];
    	    ny=y+posY[i];
    	    if (nx>=0 && nx <= max && ny>=0 && ny<=max){

           f(nx,ny);

    	    }
    }
}

int main()
{
	int i;
	for (i=1; i <= 10; i++)
	{
		count=0;
		max=i;
	    f(0,0);
	    printf("%ld ",count);
	}
	return 0;
}


继续做分析如下:



因为只能往右和往下走,而且在一个小格中,任意位置上的路径和等于左边的点和上面的点上和,在图中的第一个小格子中,最右下角的路径和等于a+b路径上的和,那么就可以写出递归式子:

#include <stdio.h>

unsigned long f(int x,int y){
	if(x==0 || y==0)
		return 1;
	
	f(x-1,y)+f(x,y-1);
}

int main()
{
    int i=1;
	printf("%ld   ",f(20,20));
    return 0;
}


不过跑了一会还是没有跑出结果,于是我继续优化。当你求的点x,y 如果x==y的话,那么即是一个正方形的格子,正方形的格子可以对折,即左下角的点等于右上角的点,那么这里我又优化了一下,这里是一个大优化,切断了大半的递归函数。

#include <stdio.h>

unsigned long f(int x,int y){
	if(x==0 || y==0)
		return 1;
	if(x==y) return 2*f(x-1, y);
	else return f(x-1,y)+f(x,y-1);
}

int main()
{
    int i=1;
	printf("%ld   ",f(20,20));
    return 0;
}


最后貌似等了1分钟左右,终于出来了,结果是正确的,我是一个很懒的人,出了结果就不想优化了,哪个小伙伴发现了其他的方法记得留言哦!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: