

You are given two binary grids ‘MAT1’ and ‘MAT2’ of size N x N each. Both grids either have 0 or 1 written in each cell.
You can perform four types of operations to MAT1-
• Right Shift
• Left Shift
• Up Shift
• Down Shift
For eg:
Let the grid MAT1 be-

After one right shift, it will look like-

After one left shift, it will look like-

After one up shift, it will look like-

After one down shift, it will look like-

You can perform any of the above operations in any order, any number of times(possibly zero) to MAT1.
Overlap of two grids is defined as the number of cells which have 1 written in it, in both the grids. Your task is to find the maximum possible overlap between ‘MAT1’ and ‘MAT2’ after applying some operations to ‘MAT1’.
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test case follows.
The first line of each test case contains one integer ‘N’ denoting the number of rows and columns in the grid ‘MAT1’ and ‘MAT2’.
The next ‘N’ lines of each test case contain ‘N’ space-separated integers each representing the rows of ‘MAT1’
The next ‘N’ lines of each test case contain ‘N’ space-separated integers each representing the rows of ‘MAT2’.
Output Format :
For each test case, print the maximum possible overlap.
The output for each test case will be printed in a new 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 <= 30
0 <= MAT1[i][j] <= 1
0 <= MAT2[i][j] <= 1
Time Limit: 1 sec.
2
3
1 1 0
0 0 0
0 0 0
0 1 1
0 0 0
0 0 0
2
1 1
1 1
1 1
1 1
2
4
The optimal answer for the first test case:
After applying one right shift to MAT1, we get it as-
0 1 1
0 0 0
0 0 0
The overlap of MAT1 with MAT2 will be 2.
The optimal answer for the second test case:
We do not apply any shift to MAT1.
The overlap of MAT1 with MAT2 will be 4.
1
3
1 1 0
0 1 0
0 1 0
0 0 0
0 1 1
0 0 1
3
Check every cell of the grid.
For any cell A of MAT1 which has one and cell B of MAT2 which has one we can define linear transformation L as - (difference of X - coordinates of A and B, difference of Y - coordinates of A and B). The cells which come under the same overlapping zone will have the same value of L.
The algorithm will be-
O(N ^ 4), where N is the number of rows and columns of the grid.
In the worst-case, both MAT1 and MAT2 will be filled by ones and the size of array/list first and second will be at most O(N ^ 2). For each element of the first, we are iterating over each element of the second. Hence overall time complexity will be O(N ^ 4).
O(N ^ 2), where N is the number of rows and columns of the grid.
In the worst case, the size of both the first and the second can be O(N ^ 2).