Count Paths in a Grid

Problem

A robot stands in the top-left cell of a grid with a rows and b columns. It can move only right or down. Print how many different paths lead to the bottom-right cell.

Constraints

  • 1 <= rows, cols <= 15

Examples

Input

3 2

Output

3

Input

3 7

Output

28

Solutions

Best approachTime O(rows * cols)Space O(rows * cols)

To reach a cell we come from above or from the left. So paths(r, c) = paths(r-1, c) + paths(r, c-1). The memo table stops repeated work. A formula also exists: C(r + c - 2, r - 1).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count grid paths.
 * Input   : Two integers: rows and columns.
 * Output  : The number of paths.
 * Approach: Recursion with memo.
 * Time    : O(rows * cols)
 * Space   : O(rows * cols)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // Step 1: paths(rows, cols, memo) is the number of paths in a grid of that size.
        static long paths(int rows, int cols, long[][] memo) {
            // Step 2: Base case. In one row or one column there is only one path.
            if (rows == 1 || cols == 1) {
                return 1;
            }

            // Step 3: The last move was down or right. Add the paths of both smaller grids. Save the result.
            if (memo[rows][cols] == 0) {
                memo[rows][cols] = paths(rows - 1, cols, memo) + paths(rows, cols - 1, memo);
            }
            return memo[rows][cols];
        }

    // This method solves the task. It receives the input and returns the answer.
    static long solve(long a, long b) {
        return paths((int) a, (int) b, new long[(int) a + 1][(int) b + 1]);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. From which two cells can you reach a cell?