- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a N x N binary matrix where 0 is for empty cells and 1 is a blocked cells, we have to find the number of ways to choose N empty cells such that every row and every column has at least one chosen cells. If the answer is very large return result mod 10^9 + 7

So, if the input is like

0 | 0 | 0 |

0 | 0 | 0 |

0 | 1 | 0 |

then the output will be 4, as we have following configurations (where x is a selected cell) −

To solve this, we will follow these steps −

- n := size of matrix
- Define a function f() . This will take i, bs
- if i >= n, then
- return 1

- ans := 0
- for j in range 0 to n, do
- if matrix[i, j] is same as 0 and (2^j AND bs is same as 0) , then
- ans := ans + f(i + 1, bs OR 2^j)

- if matrix[i, j] is same as 0 and (2^j AND bs is same as 0) , then
- return ans
- From the main method call and return f(0, 0)

Let us see the following implementation to get better understanding −

class Solution: def solve(self, matrix): n = len(matrix) def f(i, bs): if i >= n: return 1 ans = 0 for j in range(n): if matrix[i][j] == 0 and ((1 << j) & bs == 0): ans += f(i + 1, bs | (1 << j)) return ans return f(0, 0) ob = Solution() matrix = [ [0, 0, 0], [0, 0, 0], [0, 1, 0] ] print(ob.solve(matrix))

[ [0, 0, 0], [0, 0, 0], [0, 1, 0] ]

4

- Related Questions & Answers
- Program to count how many ways we can cut the matrix into k pieces in python
- Program to find how many ways we can climb stairs in Python
- In how many ways can we split a string in JavaScript?
- Program to count how many ways we can divide the tree into two trees in Python
- In how many ways we can concatenate Strings in Java?
- In how many ways can we find a substring inside a string in javascript?
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- In how many ways we can convert a String to a character array using Java?
- Program to find number of ways we can decode a message in Python
- Program to find number of ways we can split a palindrome in python
- How many ways can we read data from the keyboard in Java?
- Program to find how many total amount of rain we can catch in Python
- How many ways can a property of a JavaScript object be accessed?
- What are JSP declarations? In how many ways we can write JSP declarations?
- Program to find maximum how many water bottles we can drink in Python

Advertisements