
Ninja considers himself a master in solving sudoku. To test his problem-solving skills, one day his friend asked him to solve a problem based on the grid. The problem is as follow :
There is a grid of ‘N’ rows and ‘M’ columns consisting of four digits 0, 1, 2, and 3.
We call a four-cell group a “lucky group” if and only if :
1. The number on these cells form a permutation of the set {0,1, 2, 3}.
2. The cell marked 1 is directly reachable from the cell marked 0.
3. The cell marked 2 is directly reachable from cell marked 1.
4. The cell marked 3 is directly reachable from cell marked 2.
Given the constraint that each cell can be part of at most 1 "lucky Group". Your task is to find the maximum number of “Lucky Group”.
Since Ninja finds this problem very different and difficult from the sudoku problem. He needs your help. Can you solve the problem on his behalf?
The first line contains one positive integer ‘T’, denoting the number of test cases, then ‘T’ test cases follow.
The first line of each test case contains two integers ‘N’ and ‘M’, denoting the number of rows and columns in a given grid.
The next ‘N’ line contains ‘M’ space-separated integers consisting of either 0, 1, 2 or 3 denoting the grid cell.
Output Format:
The first line of each test case contains one integer ‘X’, denoting the maximum number of “Lucky Group”.
The output of each test case will be printed on a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N, M <= 20
0 <= cell[i][j] <= 3
Time Limit: 1 sec.
2
2 2
0 1
3 2
2 4
0 1 2 2
0 2 3 3
1
1
In the first test case, cells (0,0) --> (0,1) -->(1, 1) --> (1, 0) form one lucky group.
In the second test case, cells (0,0) --> (0,1) -->(0, 2) --> (1, 2) form one lucky group. We can prove that there is no more than one lucky group.
2
3 4
0 1 0 1
3 2 3 2
3 0 1 3
5 2
0 1
1 1
2 3
1 1
0 0
2
1
Can you convert this question to the max-flow problem? Split the nodes with values 1 and 2 into two nodes.
This problem can be solved using maximum flow concept.
Consider the following network:
We add the following edges to our network.
Let ‘countGroup(grid, n, m)’ be the function that returns the maximum number of lucky groups.
The steps are as follows :
O(N * M) ^ 2. , where ‘N’ is the number of rows and ‘M’ is the number of columns in a given grid.
The time taken to create graph O( N * M) . The time taken to find max- flow is O( edges * maxFlow ) = O( (N * M * 2) * ( N * M / 2) ) =O (N * M) ^ 2.
O(M * N), where ‘N’ is the number of rows and ‘M’ is the number of columns in a given grid.
Mainly, We are using space in creating a graph, which takes O(N * M) space. Hence, the space complexity is O(N * M).