We are given a set of bipolar magnets, each domino-shaped. The objective is to place magnets on an M × N board, which satisfies a set of conditions where both M and N are not odd.

For instance, the following problem has the solution on its right:

Magnet Puzzle

 
Each 2 × 1 or 1 × 2 grid in the board can contain a magnet or empty. The blank entry will be indicated by X's, and the magnet will be represented by + and - (For the positive and negative end, respectively). The digits along the board’s left and top sides represent the count of + squares in corresponding rows or columns. Similarly, those along the right and bottom show the total number of - signs in particular rows or columns. Rows and columns for which no number is mentioned can have any number of + or - signs. The puzzle solution must also satisfy the constraint that no two adjacent squares can have the same sign. But diagonally joined squares can have the same sign.

Examples:

Here, top[], bottom[], left[], right[] arrays indicates the count of + or - along the top (+), bottom (-), left (+), and right (-) edges, respectively. The value of -1 indicate any number of + or - signs.

The rules[][] matrix can contain any T, B, L, or R character. T indicates its top end for a vertical slot in the board, and B indicates the bottom end. L indicates the left end, and R indicates the right end for a horizontal slot in the board.

Input:
 
top[] = [1, -1, -1, 2, 1, -1]
bottom[] = [2, -1, -1, 2, -1, 3]
left[] = [2, 3, -1, -1, -1]
right[] = [-1, -1, -1, 1, -1]
 
Rules[][] =
[L R L R T T]
[L R L R B B]
[T T T T L R]
[B B B B T T]
[L R L R B B]
 
Output:
+ – + – X –
– + – + X +
X X + – + –
X X – + X +
– + X X X –
 
 
Input:
 
top[] = [2, -1, -1]
bottom[] = [-1, -1, 2]
left[] = [-1, -1, 2, -1]
right[] = [0, -1, -1, -1]
 
Rules[][] =
[T T T]
[B B B]
[T L R]
[B L R]
 
Output:
+ X +
– X –
+ – +
– + –

Practice this problem

The idea is to use backtracking. We start from the first cell of the rules matrix and check for every horizontal and vertical slot. If the horizontal or vertical slot contains L and R or T and B, respectively, put ('+', '-') or ('-', '+') accordingly in the slot and recursively checks if they lead to the solution or not. If the solution is found with the required configuration, print the solution matrix; if none of the above solutions work, return false from the function.

 
Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
+ – + – X –
– + – + X +
X X + – + –
X X – + X +
– + X X X –

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).

 
This question is taken from – https://people.eecs.berkeley.edu/~hilfingr/programming-contest/f2012-contest.pdf