Grid of Many Xors

4.6

15 votes
Algorithms, Graphs, Medium, Minimum spanning tree
Problem

Consider a grid with N rows and M columns, where each cell has some integer value written in it. Every cell is connected to every side adjacent cell via an undirected edge. The cost of an edge e connecting any two cells with value a and b is Ce=ab. (Here denotes bitwise xor of two the integers a and b)

We define a good trip between two cells (r1,c1) and (r2,c2) as a trip starting at cell (r1,c1) and ending at cell (r2,c2) while visiting every cell of the grid at least once.

There is a cost associated with every good trip. Let's say, for a given edge e, you travel that edge Te times. Then the cost of the trip is:

e(CeTe2)

Here, Te2 is the ceiling of the result of division of Te by 2

For the given starting cell (r1,c1) and ending cell (r2,c2), you have to find the minimum cost of a good trip.

Input Format

The first line will consist of the integer T denoting the number of test cases.

For each of the T test cases, the first line will consist of two integers N and M, denoting the number of rows and columns of the grid respectively.

The second line will consist of four integers, r1c1r2c2, denoting the coordinates (r1,c1) of the starting cell and (r2,c2) of the ending cell.

Then, N lines will follow, each containing M integers, denoting the values in the grid, such that the jth value in the ith row will denote the number in the cell (i,j) of the grid.

Output Format

For each of the T test cases, output a single integer, denoting the minimum cost of a good trip.

Constraints

1T10

1N×M105

1r1,r2N

1c1,c2M

1Grid(i,j)104

where Grid(i,j) denotes the integer in the given grid at cell (i,j).

Sample Input
2
2 2
1 1 2 1
1 2
2 2
1 3
1 2 1 3
1 3 4
Sample Output
3
9
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

For the first test case, the grid looks as follows:

enter image description here

You can take a trip (1,1)(1,2)(2,2)(2,1)

Since you will use the edge between (1,1)(1,2) one time, you will have to pay (12)12=3 for that edge.

For the other edges, the edge cost is 0 (since 22=0).

Therefore the total cost for the good trip shown in the figure is 3.

Editor Image

?