Light Up
Time limit2sMemory limit256 MB
Place bulbs on white cells of an N by N Light Up board so every white cell is lit and each numbered black cell has the required count of adjacent bulbs, choosing the lexicographically smallest solution.
- Level
Medium7 of 10
- Topics
- Backtracking, Brute force, Implementation, Matrix
- Solved
- No attempts yet
Problem
Light Up is a puzzle played on a square board. Each cell of an board is either a black square or a white square. The goal is to place light bulbs on some white squares so that every white square is lit.
A white square is lit when a bulb stands in the same row or the same column and no black square lies between them. A square that holds a bulb is lit as well. A bulb can be placed only on a white square.

Figure 1
Placing a bulb at on the board of figure 1 gives the situation in figure 2.

Figure 2
Placing a bulb on a white square that is already lit overheats the bulb, so such a placement is not allowed. Bulbs at both and , as in figure 3, are impossible.

Figure 3
Some black squares carry a digit. The digit is the number of squares that must hold a bulb among the squares sharing an edge with that black square. Look at the board in figure 4.

Figure 4
Figure 5 shows one placement that satisfies every rule on the board of figure 4.

Figure 5
Given a board, find a placement that solves the puzzle.
Input
The first line holds the number of test cases . ()
The first line of each test case holds the board size . ()
Each of the next lines holds integers separated by a space. The -th integer of the -th line is the description of the cell at . A value of means a white square, means a black square with no digit, and a value from to means a black square carrying that digit.
Output
For each test case print lines, each holding integers equal to or and separated by a space. Print for a cell that holds a bulb and for a cell that does not. Print the answers of the test cases in the order the boards are given.
Every input has at least one valid placement. When more than one placement satisfies the rules, print only the lexicographically smallest one. Read a placement from the first line to the last, and inside a line from left to right, as a sequence of digits and . The answer is the placement whose sequence is smallest in lexicographic order. In other words, walking the cells in that order, a cell holds whenever the puzzle can still be finished with in it.