xamples
epeat
ode
pproach
ptimize
est
Given a square grid, how could you determine the number of possible paths from the top left of the grid to the bottom right, assuming you can only move to the right and down?
Example: a 2 by 2 grid has 6 possible paths
Same Approach, Different View
(0,0)
(1,0)
(0,1)
(2,0)
(1,1)
(0,2)
(2,1)
(2,2)
(1,1)
(1,2)
(2,2)
(2,1)
(2,1)
(1,2)
(2,2)
(2,2)
(2,2)
(2,2)
(1,2)
function paths2Bottom(x, y, max){
if (x == max || y == max){
return 1;
}
return paths2Bottom(x+1, y, max) + paths2Bottom(x, y+1, max);
}
var paths = {};
function memoizer(x, y, max){
if(paths[[x,y,max]]){
return paths[[x,y,max]];
}
else{
return paths[[x,y,max]] = paths2Bottom(x, y, max);
}
}
function paths2Bottom(x, y, max){
if (x == max || y == max){
return 1;
}
return memoizer(x+1, y, max) + memoizer(x, y+1, max);
}
When mapping the possible paths, you might see a pattern -- Pascal's Triangle!
We also know that when you hit the right or bottom edge of a grid, there is only one possible path.
var paths = {};
function memoizer(x, y, max){
if(paths[[x,y,max]]){
return paths[[x,y,max]];
}
else{
return paths[[x,y,max]] = paths2Bottom(x, y, max);
}
}
function paths2Bottom(x, y, max){
if (x == max || y == max){
return 1;
}
return memoizer(x+1, y, max) + memoizer(x, y+1, max);
}
Solution on Repl.it
Source from Project Euler