Lattice paths
Problem 15
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?
Link: https://projecteuler.net/problem=15
My solution:
Using recursie function to find out the routes.
Implemented by Lu.Qian. using C++:
1 #include <iostream> 2 //#include <cstring> 3 //#include <cmath> 4 //#include <map> 5 using namespace std; 6 7 unsigned long long int num = 0; 8 void find_route(int len, int wid){ 9 if(len == 0 || wid == 0){ 10 num++;
return; 11 } 12 find_route(len - 1, wid); 13 find_route(len, wid - 1); 14 } 15 16 int main() 17 { 18 19 find_route(20,20); 20 cout<<num<<endl; 21 return 0; 22 }
However, this project I worte will take so much cost on recurive funciton, and the running time it take will be unacceptable.
So I'll wirite another function by using simple iteration.
I implemented it by python and usd a container 'dict' to eliminate duplicate computating.
1 c = {} 2 def countRoutes(m,n): 3 if n == 0 or m == 0: 4 return 1 5 6 if c.has_key((m,n)): 7 return c[(m,n)] 8 9 c[(m,n)] = countRoutes(m, n-1) + countRoutes(m-1,n) 10 return c[(m,n)]
The iterative solution is also using container (two-dimensional array) to fulfill the container from bottom to up.
Here is the pseudocode for iterative solution:
function countRoutes(m,n) grid array[m + 1][n + 1] // A two-dimensional 0-indexed array of size m + 1 by n + 1 for i = 0 to m do grid[i][0] 1 end for for j = 0 to n do grid[0][j] 1 end for for i = 1 to m do for j = 1 to n do grid[i][j] grid[i − 1][j] + grid[i][j − 1] end for end for return grid[m][n] end function
This problem has another approach to solve - combinatorial solution. This gives us a much faster O(n) solution.
Acknowledgement:
All the algorithms which give O(mn) or O(n) are from Pim Spelier's work.