We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Mathematics
- Fundamentals
- Matrix Tracing
- Discussions
Matrix Tracing
Matrix Tracing
Sort by
recency
|
59 Discussions
|
Please Login in order to post a comment
Interesting combinatorics problem since every valid path forms the same word, the task reduces to counting paths in an m × n grid moving only RIGHT or DOWN, which is a classic binomial coefficient calculation; platforms like LemTask often frame such challenges to test mathematical insight over brute force. The total number of tracings is C(m+n-2, m-1) modulo 10^9+7, ensuring efficiency even for very large constraints.
MOD = 10**9 + 7
def precompute(max_n): fact = [1] * (max_n + 1) inv_fact = [1] * (max_n + 1) for i in range(2, max_n + 1): fact[i] = fact[i-1] * i % MOD inv_fact[max_n] = pow(fact[max_n], MOD-2, MOD) for i in range(max_n-1, -1, -1): inv_fact[i] = inv_fact[i+1] * (i+1) % MOD return fact, inv_fact
def nCr(n, r, fact, inv_fact): if r < 0 or r > n: return 0 return fact[n] * inv_fact[r] % MOD * inv_fact[n-r] % MOD
def solve(): t = int(input().strip()) cases = [] max_mn = 0 for _ in range(t): m, n = map(int, input().split()) cases.append((m, n)) max_mn = max(max_mn, m + n)
if name == "main": solve()
This works. Hint: 10^9 +7 is prime
`
This is a combinatorial problem number of ways to move from top-left to bottom-right using only right and down moves is given by C(m+n−2, m−1). So the total tracings = (m+n−2)! / ((m−1)! * (n−1)!). For large values, take result mod (10^9+7). For example, m=2, n=3 → C(3,1)=3.
import sys
MAX_R = 2000001 MOD = 10**9 + 7 FACT = [1] * MAX_R
def power(a, b): res = 1 a %= MOD while b > 0: if b % 2 == 1: res = (res * a) % MOD a = (a * a) % MOD b //= 2 return res
def modInverse(n): return power(n, MOD - 2)
def precompute_factorials(): for i in range(2, MAX_R): FACT[i] = (FACT[i-1] * i) % MOD
def combinations(n, k): if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 if k > n // 2: k = n - k
def solve_matrix_tracing(M, N): R = M + N - 2 K = M - 1
if name == 'main': precompute_factorials()