
Given:
‘M’ = 3, ‘N’ = 3.
‘SEATS’ = {
{‘.’, ‘.’, ‘.’},
{‘#’,’#’, ‘#’},
{‘.’,’.’,’.’}
}
The answer will be 4, since 4 students can be placed at the four corners, i.e. (0,0), (2,2), (2,0), and (0,2) such that no cheating is possible.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘M,’ where ‘M’ is the number of rows in ‘SEATS’ and ‘N’ where ‘N’ is the number of columns in ‘SEATS’.
The next ‘M’ line contains ‘N’ space-separated integers which tell if the seat is broken or in good condition.
For each test case, You are supposed to return an integer that denotes the maximum number of students that can be placed such that no cheating is possible.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10
1 <= ‘M’ <= 10
Time Limit: 1sec.
In computing, numbers are internally represented in binary. This means, where you use an integer type for a variable, this will actually be represented internally as a summation of zeros and ones.
Bit masking allows you to use operations that work on bit-level.
You apply a mask to a value, wherein in our case the value is our state 00000101 and a mask is again a binary number, which indicates the bits of interest.
The idea is to use a bitmask to denote the state of each row, where 1 denotes that the seat is good and students can be placed there and 0 denotes that the seat is broken.
When we arrange for the students to sit in this row, we can also use ‘N’ bits to represent the students. The i-th bit is 1 if and only if the i-th seat is occupied by a student. We should notice that n bits representing students must be a subset of ‘N’ bits representing seats.
Since there will be recurring problems, we use a ‘dp[i][j]’ table to store and cache the states, where ‘i’ denotes the row and ‘j’ is the ‘mask’ of seated students.
We denote ‘dp[i][mask]’ as the maximum number of students for the first ‘i’ rows while the students in the i-th row follow the masking mask. There should be no adjacent valid states in the mask. The transition function is:
‘dp[i][mask]’ = max(‘dp[i - 1][mask']’) + number of valid bits(mask)
where mask' is the configuration of students for the (i-1)-th row. To prevent students from cheating, the following equation must hold:
If these two equations hold and ‘dp[i - 1][mask']’ itself is valid, we could then transition from ‘dp[i - 1][mask']’ to ‘dp[i][mask]’ according to the transition function.
The steps are as follows: