GeeksforGeeks » Interview Questions
Balanced 0-1 matrix
(3 posts)-
Given an n*n matrix --->in how many ways we can fill n/2 0 and n/2 1 in each and every column....!!
-
The no of ways a given column can be formed:
a.Place all n/2 0's at a stretch.now ,there are (n/2+1) gaps between the 0's and each 1 can go in any of these gaps.So,total no of ways of getting a column=(n/2+1)*(n/2)Now ,to get complete matrix we allow for each of the n columns to have any of these (n/2+1)*(n/2) configurations giving a total of (n/2+1)*(n/2)*n
-
this is the balance 0/1 matrix which can be solved either by bruteforce or backtracking or by dynamic programming.
Dynamic programming makes it possible to count the number of solutions without visiting them all. Imagine backtracking values for the first row - what information would we require about the remaining rows, in order to be able to accurately count the solutions obtained for each first row values? We consider k × n boards, where 1 ≤ k ≤ n, whose k rows contain n / 2 zeros and n / 2 ones. The function f to which memoization is applied maps vectors of n pairs of integers to the number of admissible boards (solutions). There is one pair for each column and its two components indicate respectively the number of ones and zeros that have yet to be placed in that column. We seek the value of (n arguments or one vector of n elements). The process of subproblem creation involves iterating over every one of possible assignments for the top row of the board, and going through every column, subtracting one from the appropriate element of the pair for that column, depending on whether the assignment for the top row contained a zero or a one at that position. If any one of the results is negative, then the assignment is invalid and does not contribute to the set of solutions (recursion stops). Otherwise, we have an assignment for the top row of the k × n board and recursively compute the number of solutions to the remaining (k - 1) × n board, adding the numbers of solutions for every admissible assignment of the top row and returning the sum, which is being memoized. The base case is the trivial subproblem, which occurs for a 1 × n board. The number of solutions for this board is either zero or one, depending on whether the vector is a permutation of n / 2 (0,1) and n / 2 (1,0) pairs or not.
Reply
You must log in to post.