歐拉計劃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;
}
發佈了84 篇原創文章 · 獲贊 9 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章