Ways of filling matrix such that product of all rows and all columns are equal to unity | Java program to find number of ways to fill a matrix under given constraints ; Returns a raised power t under modulo mod ; Counting number of ways of filling the matrix ; Function calculating the answer ; if sum of numbers of rows and columns is odd i . e ( n + m ) % 2 == 1 and k = - 1 , then there are 0 ways of filiing the matrix . ; If there is one row or one column then there is only one way of filling the matrix ; If the above cases are not followed then we find ways to fill the n - 1 rows and m - 1 columns which is 2 ^ ( ( m - 1 ) * ( n - 1 ) ) . ; Driver function for the program
import java . io . * ; class Example { final static long mod = 100000007 ; static long modPower ( long a , long t , long mod ) { long now = a , ret = 1 ; while ( t > 0 ) { if ( t % 2 == 1 ) ret = now * ( ret % mod ) ; now = now * ( now % mod ) ; t >>= 1 ; } return ret ; } static long countWays ( int n , int m , int k ) { if ( n == 1 m == 1 ) return 1 ; else if ( ( n + m ) % 2 == 1 && k == - 1 ) return 0 ; return ( modPower ( modPower ( ( long ) 2 , n - 1 , mod ) , m - 1 , mod ) % mod ) ; } public static void main ( String args [ ] ) throws IOException { int n = 2 , m = 7 , k = 1 ; System . out . println ( countWays ( n , m , k ) ) ; } }