python - Code to find number of route-combinations in a N by N grid -
i have write code has count number of different combinations start upper left of n n grid, , end in lower right corner. can go down , right!
so (if give each of vertices number 1 - (n+1)^2), how many different combinations there 1 - (n+1)^2. can add 1 or add n+1.
an example: 2x2 grid:
1 -- 2 -- 3 | | | 4 -- 5 -- 6 | | | 7 -- 8 -- 9
and combinations be:
[1-2-3-6-9] [1-2-5-6-9] [1-2-5-8-9] [1-4-5-6-9] [1-4-5-8-9] [1-4-7-8-9]
now, how should write code? appreciated!
in advance
ah. see trying on 1 of eulerproject problems? point manage figure out , learn new things along way! tricking cheating. oh well
anyways, consider grid of m rows , n columns (we not need assume grid square). counting upper-left , starting @ zero, denote intersection/node in i-th row , j-th column n_(i,j).
thus, upper-left node n_(0,0), bottom-left n_(m,0) , bottom-right n_(m,n). clearly, number of paths n_(0,0) node along far right or far top of grid 1 (since may proceed down or right).
now, consider how many paths there n_(1,1). must first travel through n_(0,1) or n_(1,0). yields 2 paths n_(1,1). can continue process. in order determine total number of paths node n_(i,j), need sum total number of paths n_(i,j−1) , n_(i−1,j). process understood graphically in following diagram, each new integer represents number of paths node.
if code in python get:
def route_num(cube_size): l = [1] * cube_size in range(cube_size): j in range(i): l[j] = l[j]+l[j-1] l[i] = 2 * l[i - 1] return l[cube_size - 1]
print route_num(20) give 137846528820.
source: http://code.jasonbhill.com/
Comments
Post a Comment