A Square Grid Path Problem
Last November I solved Problem 15 of Project Euler (a counting problem involving paths in square grids), and, although the problem admits a simple solution, some of the solutions presented in their forums are very complicated. Thus, I thought it would be a good idea to present my solution, as I consider it very simple.
Problem statement
Starting in the top left corner of a
How many routes are there through a 20×20 grid?
My solution
In order to make the problem more interesting, let us investigate the more
general problem of counting the number of routes in an
all the paths have size
(the reason is obvious: you have to go right positions and down another positions);since we can only go right or down, we can identify every path by a string of Rs and Ds, where an R means going right and a D means going down; as an example, the paths illustrated in the problem statement are (from left to right and from top to bottom): RRDD, RDRD, RDDR, DRRD, DRDR and DDRR;
the strings mentioned above must contain the same number of Rs and Ds.
From these three observations, we can transform the problem to the following:
How many different strings of size
The solution is now very simple, because the positioning of
Instantiating
Generalization to grids
The generalization to an
Final note: If you want to access the forum of the problem, you have to solve it.