Project Euler : Problem 15 - Lattice paths

3 minute read

Problem Statement : 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.

image-center How many such routes are there through a 20×20 grid?

Concept and Theory

image-center

One can see from the above diagram, the number of routes from to is equal to the number of routes from to plus the number of routes from to . A very simple recursive algorithm can be written based on the above observation.

Recursive Programming

/**
 * A function which returns the number of the path from one corner to other
 * corner in a grid
 *
 * @param n : length of the grid
 *
 * @param m : height of the grid
 *
 * @return number of the paths
 */
public static int countRoutes(int n, int m) {
  if (n == 0 || m == 0) {
    return 1;
  } else {
    return countRoutes(n, m - 1) + countRoutes(n - 1, m);
  }
}

But again the problem is that we are recomputing some points again and again. Cache them!!!

Dynamic Programming

/**
 * A function which tells the number of ways of reaching the bottom right corner
 * from top left corner
 *
 * @param n : width of the grid
 *
 * @param m : height of the grid
 *
 * @return the numbers of ways
 */
public static long getTotalPath(int n, int m) {
  long M = 1000000007L;
  long[][] grid = new long[n + 1][m + 1];

  for (int i = 0; i <= n; i++) {
    for (int j = 0; j <= m; j++) {
      if (i == 0 || j == 0) {
        grid[i][j] = 1;
      } else {
        grid[i][j] = (grid[i - 1][j] + grid[i][j - 1]) % M;
      }
    }
  }

  return grid[n][m];
}

Mathematical Approach

Since we can only move right or down, we will be needing steps right and steps down always, to reach the bottom corner. So the number of combinations of rights and down moves is our answer. Thus the formula for such combination is given as,

A single configuration, once we place the the right movements we immediately know where the downward movements must go (as they cannot go anywhere else). All we really have to know is how many ways we can place the right movements. The number of ways we can do this, mathematically, is denoted with the binomial coefficient .

Mathematically choosing elements from elements is given as follows,

Using this formula we can calculate ,

When

Test Your Skills

Wanna try a harder version of the above problem ? Check this HackerRank problem.

Solution

The solution will remain same as given in the above mentioned post, , you just need to call it for each test case.

References and Further Readings

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...