You have a rectangular grid of points with n rows and n columns. You start at the bottom left corner. At each step, you can either go up to the next point in the same column or right to the next point in the same row. How many such paths are there from the bottom left corner to the top right corner?
Solution
We have to take 2n steps, of which we have to choose n to be up moves and n to be right moves. This gives (2n choose n) paths.
Instead, we can use a recursive formulation:
This is a recurrence relation. Solving this naively is inefficient, because Path(i,j) will be recomputed several times.
Instead, start at bottom left corner and compute the values along diagonals with points (i,j) where i+j is constant. Write a loop to store these values in an array. Takes time proportional to n*n (each grid point is updated exactly once and read upto twice).
One way to structure the solution as a simple nested loop is:
for c = 0 to n*n for each (i,j) such that i+j = c update Path(i,j) using Path(i-1,j) and Path(i,j-1)
This way, whenever a new value Path(i,j) has to be computed, the values it depends on --- Path(i-1,j) and Path(i,j-1) --- are already known.
Why is the recursive solution better?
What if some points are deleted (that is, no path can go through these points)?
If there is one deleted point, we have to subtract the number of paths that pass through these points.
In general, holes may be arbitrarily complicated: if we have two holes, we subtract number of paths that pass through either hole, but we have then subtracted twice the paths that go through both holes, so we have to add these back.
Instead, we can modify the recurrence to take into account the holes.
Video lecture on Grid paths, NPTEL online course on Design and Analysis of Algorithms (Lecture slides)
©IARCS 2012–2016
Pěstujeme web | visit: Skluzavky