# Program to count number of possible humble matrices in Python

Suppose we have two values n and m. We have to find number of possible arrangements of humble matrices of order n x m. A matrix is said to be humble when

• It contains each element in range 1 to n x m exactly once
• for any two indices pairs (i1, j1) and (i2, j2), if (i1 + j1) < (i2 + j2), then Mat[i1, j1] < Mat[i2, j2] should hold.

If the answer is too large then return result mod 10^9 + 7.

So, if the input is like n = 2 m = 2, then the output will be 2, because there are two possible matrices -

 1 2 3 4

And

 1 3 2 4

To solve this, we will follow these steps −

• p := 10^9+7
• result := a list with value 1
• for x in range 2 to 10^6, do
• temp := last element of result
• temp :=(temp*x) mod p
• insert temp at the end of result
• if m > n, then
• temp := n
• n := m
• m := temp
• prod := 1
• for x in range 1 to m, do
• prod :=(prod * result[x-1]) mod p
• prod := (prod^2) mod p
• for x in range 0 to n - m, do
• prod := (prod * result[m-1]) mod p
• return prod

## Example

Let us see the following implementation to get better understanding −

p = 10**9+7

def solve(n, m):
result = 
for x in range(2,10**6+1):
temp = result[-1]
temp = (temp*x) % p
result.append(temp)

if(m > n):
temp = n
n = m
m = temp
prod = 1
for x in range(1,m):
prod = (prod * result[x-1]) % p
prod = (prod**2) % p
for x in range(n-m+1):
prod = (prod*result[m-1]) % p
return prod

n = 3
m = 3
print(solve(n, m))

## Input

3, 3


## Output

24

Updated on: 23-Oct-2021

74 Views 