Bar Code
Time limit10sMemory limit1024 MB
Given the group counts for each row and column, place non-touching bars on the n by n grid borders so every line matches its specification.
- Level
Medium5 of 10
- Topics
- Backtracking, Implementation
- Solved
- No attempts yet
Problem

Bar Code is a puzzle invented by Thinh Van Duc Lai in 2017. The New York Times first published it.
The puzzle is played on a square grid of unit squares, which has grid points. For a given specification, mark some of the borders of the unit squares by drawing a vertical or horizontal bar. The markings must satisfy these conditions:
- For each row and column, the specification gives how many separate groups of consecutive bars of the same orientation there must be. For example, the specification
2 1 1requires 3 groups of 2, 1, and 1 bars, with at least one unmarked border between groups. - No 2 bars may touch.
For example, here is a puzzle with borders in each row. The following markings meet this specification:
1101010
1101001
1100101
0110101
Here 1 denotes a bar and 0 denotes an unmarked border.
The illustration shows the solution for sample input 3.
Input
The first line contains an integer (). The next lines describe the vertical bars. Line lists the group sizes for row , counting from the top. Each line has one or more non-negative integers. If a line is the single integer 0, no borders may be marked in that row. Otherwise, none of the integers on the line is 0.
The following lines describe the horizontal bars. Line lists the group sizes for column , counting from the left, in the same format.
Output
Print strings of length for the vertical borders. The -th character of the -th string is 1 if the -th vertical border in row is a bar, and 0 otherwise.
Then print strings of length for the horizontal borders. The -th character of the -th string is 1 if the -th horizontal border in column is a bar, and 0 otherwise.
Rows are counted from top to bottom, and columns from left to right. If several solutions exist, you may print any of them. You may assume that at least one valid marking exists.