Matrix Tracing
Difficulty: Hard

A word from the English dictionary is taken and arranged as a matrix. e.g. "MATHEMATICS"

    MATHE  
    ATHEM  
    THEMA  
    HEMAT  
    EMATI  
    MATIC  
    ATICS  

There are many ways to trace this matrix in a way that helps you construct this word. You start tracing the matrix from the top-left position and at each iteration, you either move RIGHT or DOWN, and ultimately reach the bottom-right of the matrix. It is assured that any such tracing generates the same word. How many such tracings can be possible for a given
word of length m+n-1 written as a matrix of size m * n?

**Input Format**  
The first line of input contains an integer T. T test cases follow.  
Each test case contains 2 space separated integers m & n (in a new line) indicating that the matrix has m rows and each row has n characters.  

**Constraints**  
1 <= T <= 10<sup>3</sup>  
1 ≤ m,n ≤ 10<sup>6</sup>

**Output Format**  
Print the number of ways (S) the word can be traced as explained in the problem statement.
If the number is larger than 10<sup>9</sup>+7,   
print  `S mod (10^9 + 7)` for each testcase (in a new line). 

**Sample Input**

    1
    2 3

**Sample Output**

    3

**Explanation**  
Let's consider a word AWAY written as the matrix

    AWA
    WAY

Here, the word AWAY can be traced in 3 different ways, traversing either RIGHT or DOWN.

    AWA
      Y

    AW
     AY

    A
    WAY

Hence the answer is 3.

**Timelimit**
Time limit for this challenge is given [here](https://www.hackerrank.com/environment)

Input Format:

Output Format:

Sample Input:

Sample Output:

Python 3 starter code:
#
# Complete the 'solve' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. INTEGER m
#

def solve(n, m):
    # Write your code here



Editorial: Matrix Tracing : Codesprint 5 Editorial 
<style id="MathJax_SVG_styles">.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%}
.MathJax_SVG .MJX-monospace {font-family: monospace}
.MathJax_SVG .MJX-sans-serif {font-family: sans-serif}
.MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0}
.MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none}
.mjx-svg-href {fill: blue; stroke: blue}
</style><svg style="display: none;"><defs id="MathJax_SVG_glyphs"></defs></svg><p><a href="https://www.hackerrank.com/contests/codesprint5/challenges/matrix-tracing">Matrix Tracing</a></p>

<p><strong>Difficulty Level</strong> : Easy-Medium <br>
<strong>Required Knowledge</strong> : Combinatorics, Counting, Inverse modulo operation <br>
<strong>Problem Setter</strong> : <a href="https://www.hackerrank.com/dheeraj">Dheeraj</a> <br>
<strong>Problem Tester</strong> : <a href="https://www.hackerrank.com/abhiranjan">Abhiranjan</a>  </p>

<p><strong>Approach</strong> </p>

<p>Firstly we note that we are given a grid, and only possible ways to reach from top left to bottom right is a DOWN move and RIGHT move. <br>
It can be observed that that from each point there are always a DOWN and LEFT move (if it doesn't go off board). So given m,n in total we have m-1 RIGHT moves and n-1 LEFT moves. And imagine we auto-move RIGHT and just have to choose when to move DOWN. </p>

<p>So from m+n-2 total moves we choose m-1 down moves. Hence total ways comes out to be <sup>m+n-2</sup>C<sub>m-1</sub>. </p>

<p>Another way to look at is m+n-2 total moves where m-1 are of one type and n-1 are of another type </p>

<p>Hence total number of move is: <code>(m+n-2)!/(m-1)!(n-1)!</code></p>

<p>As we have to print ans mod 10<sup>9</sup>+7, answer should go as</p>

<pre><code>moves = (m+n-2)! / (m-1)! (n-1)!               % (10^9+7)
      = (m+n-2)! * (m-1)!^(-1) * (n-1)!^(-1)   % (10^9+7)
</code></pre>

<p>For this we need to separately calculate Numerator and Denominator using modular and inverse modular operation. </p>

<p><strong>Factorial</strong> <br>
To calculate the factorial we use the following property</p>

<pre><code>(a*b) mod m = ((a mod m)*(b mod m)) mod m
</code></pre>

<p>to calculate factorial as </p>

<pre><code>fact(0) = 1
fact(n) = fact(n-1)*n % (10^9+7)
</code></pre>

<p><strong>Inverse</strong> <br>
Fermat's Little theorem says that</p>

<pre><code>a^(p-1) == 1       mod p

where p is prime
      gcd(a, p) != 1
</code></pre>

<p>Multiplying both sides by <code>a^(-1)</code>, we get</p>

<pre><code>a^(p-1) * a^(-1) == a^(-1)     mod p
a^(p-2) == a^(-1)              mod p
a^(-1)  == a^(p-2)             mod p
</code></pre>

<p><strong>Larger Powers</strong> <br>
For calculating larger powers we use the following property</p>

<pre><code>      1                  , m == 0
a^m = (b*b)   % p        , even m
      (b*b*a) % p        , odd m

where
      b = a^floor(m/2)
</code></pre>

<p>In this way we can calculate <code>a^m</code> in <code>log(m)</code> steps.</p>

<p><strong>Final Solution</strong>  </p>

<p>So, we can rewrite our above equation as</p>

<pre><code> moves = (m+n-2)! * (m-1)!^(-1) * (n-1)!^(-1)   % (10^9+7)
       = (m+n-2)! * (m-1)!^(p-2) * (n-1)!^(p-2) % (10^9+7)
</code></pre>

<p><strong>Setter's Solution</strong>  </p>

<pre><code>#!/usr/bin/py
mod = 10**9 + 7

def getfactmod(b):
  val = 1
  for i in range(1,b):
    val =((val%mod)*((i+1)%mod))%mod
  return val

def getpowermod(a,b):
  if b==0:
    return 1
  if b == 1:
    return a
  temp = getpowermod(a,b/2)
  if b%2==0:
    return ((temp%mod)**2)%mod
  else:
    return (a*((temp%mod)**2))%mod

def inversemod(a):
  return getpowermod(a,mod-2)

if __name__ == '__main__':
  t = input()
  assert 1 &lt;= t &lt;= 10**3
  for _ in range(t):
      a,b = map(int, raw_input().strip().split(' '))
      assert 1 &lt;= a &lt;= 10**6
      assert 1 &lt;= b &lt;= 10**6
      denominator = 1
      numerator = 1
      for i in range(1, a+b-1):
          numerator = ((numerator%mod)*(i%mod))%mod
      for i in range(1, a):
          denominator = ((denominator%mod)*(i%mod))%mod
      for i in range(1, b):
          denominator = ((denominator%mod)*(i%mod))%mod
      answer = ((numerator%mod)*(inversemod(denominator)%mod))%mod
      print answer
</code></pre>

<p><strong>Tester's Solution</strong>  </p>

<pre><code>#include &lt;bits/stdc++.h&gt;
using namespace std;

const int sz = 2e6;
const long long mod = 1e9+7;

long long fact[sz];

long long _pow(int a, int b) {
    if(b == 0)
        return 1ll;
    long long ret = _pow(a, b/2);
    ret = (ret*ret) % mod;
    ret = (ret+mod)% mod;
    if(b%2 == 1)
        ret = (ret*a) % mod;
    ret = (ret+mod)% mod;
    assert(ret &gt;= 0);
    assert(ret &lt; mod);
    return ret;
}

long long inv(int a) {
    a%= mod;
    a = (a+mod)%mod;
    return _pow(a, mod-2);
}

int main()
{
    fact[0] = 1;
    for(int i = (int)1; i &lt;= (int)sz-1; ++i) {
        fact[i] = (fact[i-1]*i) % mod;
    }
    int test;
    scanf("%d", &amp;test);
    assert(test &gt;= 1);
    assert(test &lt;= 1e3);
    while(test--) {
        int n, m;
        cin &gt;&gt; n &gt;&gt; m;
        assert(1 &lt;= n); assert(n &lt;= 1e6);
        assert(1 &lt;= m); assert(m &lt;= 1e6);
        n--; m--;
        long long ans =  fact[n+m];
        ans = (ans*inv(fact[n])) % mod;
        ans = (ans + mod) % mod;
        ans = (ans*inv(fact[m])) % mod;
        ans = (ans + mod) % mod;
        assert(ans &gt;= 0);
        assert( ans &lt; mod);
        cout &lt;&lt; ans &lt;&lt; "\n";
    }

    return 0;
}
</code></pre>

Reference solution (C++):
###C++  
```cpp  
#include <bits/stdc++.h>
using namespace std;
    
const int sz = 2e6;
const long long mod = 1e9+7;
    
long long fact[sz];
    
long long _pow(int a, int b) {
    if(b == 0)
        return 1ll;
    long long ret = _pow(a, b/2);
    ret = (ret*ret) % mod;
    ret = (ret+mod)% mod;
    if(b%2 == 1)
        ret = (ret*a) % mod;
    ret = (ret+mod)% mod;
    assert(ret >= 0);
    assert(ret < mod);
    return ret;
}
    
long long inv(int a) {
    a%= mod;
    a = (a+mod)%mod;
    return _pow(a, mod-2);
}
    
int main()
{
    fact[0] = 1;
    for(int i = (int)1; i <= (int)sz-1; ++i) {
        fact[i] = (fact[i-1]*i) % mod;
    }
    int test;
    scanf("%d", &test);
    assert(test >= 1);
    assert(test <= 1e3);
    while(test--) {
        int n, m;
        cin >> n >> m;
        assert(1 <= n); assert(n <= 1e6);
        assert(1 <= m); assert(m <= 1e6);
        n--; m--;
        long long ans =  fact[n+m];
        ans = (ans*inv(fact[n])) % mod;
        ans = (ans + mod) % mod;
        ans = (ans*inv(fact[m])) % mod;
        ans = (ans + mod) % mod;
        assert(ans >= 0);
        assert( ans < mod);
        cout << ans << "\n";
    }
    
    return 0;
}
    
```