Represent unknown, zero and one separately
Use minus one for an unknown cell, zero for a placed 0, and one for a placed 1. A truthiness test would confuse a valid zero with an empty cell. The parser accepts dots or underscores as blanks and converts only those characters into minus one.
Each input line represents one row. Spaces between symbols are allowed. The parser rejects unsupported characters, odd dimensions and nonsquare input before searching. This teaching version accepts even squares from 4x4 through 12x12. Our tiny fixtures use 4x4 so you can inspect every crossing line by hand.
Flattening the board makes a cell index equal to row times width plus column, using zero-based coordinates internally. The printed trace converts those coordinates back to familiar one-based labels such as R3C2. Keep the conversion in one place to avoid shifting an error report by one cell.
Validate and propagate complete line candidates
Generate all binary strings of the chosen line length. Keep a string only when half its entries are ones and none of its three-cell windows is constant. These patterns encode balance and adjacency together. For a partial line, discard any pattern that disagrees with a known entry.
Uniqueness adds a comparison within each direction. A partial row cannot finish as an already completed peer row; the same restriction applies to columns. A row may still match a column. The program also rejects duplicate completed peers immediately, including on a fully filled input.
Every blank receives the intersection of the values supported by its row candidates and its column candidates. An empty intersection proves a contradiction. A singleton fixes the cell. Apply all such forced values, recompute the candidates, and repeat until nothing changes. This pruning does not claim to catch every impossible partial board.
Run the complete Python program
The script below uses only the Python standard library and needs Python 3.9 or later. Save the download as binary-puzzle-solver.py. No package installation, account or network connection is needed to solve a local file. The code shown here is identical to the downloadable file.
This is a readable counter for small boards. Pattern generation grows exponentially with line length, and sparse inputs can make the search expensive. There is no time or node cutoff in this example. Interrupting a run leaves its final classification unknown; do not report that interruption as zero solutions.
#!/usr/bin/env python3
"""Original teaching counter. Python 3.9+, standard library only.
Input: an even square, size 4 to 12, with 0/1 and dots or underscores.
No time/node cutoff: large sparse boards may take a long time.
"""
import argparse
import itertools
from pathlib import Path
def parse(text):
rows = [''.join(r.split()) for r in text.splitlines() if r.strip()]
n = len(rows)
if n not in range(4, 13, 2) or any(len(r) != n for r in rows):
raise ValueError('Expected an even square from 4x4 to 12x12')
if any(c not in '01._' for r in rows for c in r):
raise ValueError('Use only 0, 1, dot or underscore')
return [int(c) if c in '01' else -1 for r in rows for c in r], n
def count_solutions(board, n):
"""Return count capped at two, first answer, and a deterministic trace.
Input is unchanged. Exhausting search proves count 0 or 1.
"""
if n not in range(4, 13, 2) or len(board) != n*n:
raise ValueError('Invalid square dimensions')
if any(type(v) is not int or v not in (-1, 0, 1) for v in board):
raise ValueError('Cell values must be -1, 0 or 1')
patterns = [p for p in itertools.product((0, 1), repeat=n)
if sum(p) == n//2 and all(len(set(p[i:i+3])) > 1
for i in range(n-2))]
rows = [list(range(r*n, (r+1)*n)) for r in range(n)]
cols = [[r*n+c for r in range(n)] for c in range(n)]
def propagate(state):
while True:
domains = {i: {0, 1} for i, v in enumerate(state) if v == -1}
for group in (rows, cols):
complete = [tuple(state[i] for i in line) for line in group
if all(state[i] != -1 for i in line)]
if len(set(complete)) != len(complete):
return None
for line in group:
values = tuple(state[i] for i in line)
candidates = [p for p in patterns
if all(v == -1 or v == p[j]
for j, v in enumerate(values))
and (p == values or p not in complete)]
if not candidates:
return None
for j, i in enumerate(line):
if i in domains:
domains[i] &= {p[j] for p in candidates}
if any(not d for d in domains.values()):
return None
forced = {i: next(iter(d)) for i, d in domains.items() if len(d) == 1}
if not forced:
return domains
for i, value in forced.items():
state[i] = value
answers, trace = [], []
def search(state, depth=0):
state = state[:] # Branch owns guesses AND all propagated values.
domains = propagate(state)
prefix = ' ' * depth
if domains is None:
trace.append(prefix + 'contradiction')
return
if not domains:
answers.append(state)
trace.append(prefix + 'solution ' + str(len(answers)))
return
i = min(domains) # All surviving binary domains have two values.
for value in sorted(domains[i]):
trace.append(prefix + f'R{i//n+1}C{i%n+1} = {value}')
child = state[:]
child[i] = value
search(child, depth+1)
if len(answers) == 2:
return
search(list(board))
return len(answers), answers[0] if answers else None, trace
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', type=Path)
parser.add_argument('--trace', action='store_true')
args = parser.parse_args()
try:
board, n = parse(args.file.read_text(encoding='utf-8'))
count, answer, trace = count_solutions(board, n)
except (ValueError, OSError) as error:
parser.exit(2, str(error) + '\n')
print(('0 solutions', '1 solution', '2+ solutions')[count])
if answer is not None:
for r in range(n):
print(''.join(map(str, answer[r*n:(r+1)*n])))
if args.trace:
print('\n'.join(trace))
if __name__ == '__main__':
main()
Search with a separate state for each branch
When propagation stalls, choose the first remaining blank and explore its values in the fixed order zero, then one. All surviving cell domains have two values at that point, so this simple choice is deterministic. The program makes no claim that this order minimizes the search tree.
Each recursive call owns a copied board. That copy contains both its assumption and every value propagated from it. When a branch contradicts a rule, returning discards the whole copy. Undoing only the guessed cell would leave its consequences behind and could corrupt the next branch.
A complete assignment counts only after the same validation pass accepts every row and column. A valid-looking row alone is insufficient. Search explores disjoint cases because the chosen cell has opposite fixed values in the two branches, so the same complete answer cannot be counted in both.
Count up to two and interpret the result
Finding one answer proves existence. To establish uniqueness, continue until every remaining branch is exhausted without a second answer. If a second answer appears, stop immediately and report 2+. That output is a lower bound, not the exact number of completions of an arbitrary input.
The zero fixture fails immediately because its first row begins 000. The unique fixture has one blank in an otherwise legal board. The multiple fixture has four blanks and exactly two completions, independently established by exhaustive enumeration. The first two fixtures isolate basic rejection and acceptance; the third exercises branching and restoration.
The downloaded input files contain no headings. Put them beside the script and run the commands below. The first output line is the classification, followed by one valid answer when one exists. The optional trace records assumptions and branch outcomes.
| Input | Exact completions | Program output |
|---|---|---|
| zero | 0 | 0 solutions |
| unique | 1 | 1 solution |
| multiple | 2 | 2+ solutions |
python3 binary-puzzle-solver.py binary-puzzle-solver-zero.txt
python3 binary-puzzle-solver.py binary-puzzle-solver-unique.txt
python3 binary-puzzle-solver.py binary-puzzle-solver-multiple.txt --traceRead the small backtracking tree
The multiple-solution input is shown below. After propagation, R3C2 still permits both values. Assigning zero produces the first complete answer; assigning one produces the second. The recorded trace contains both sibling branches. You can check the printed first answer against the clues and all three classic rules. The trace records when the second answer is found.
For verification, we also enumerated every possible filled 4x4 binary board, all 65,536 of them. A separate direct rule checker agreed with the program on which complete boards were legal. The fixture checks separately confirm that counting leaves the original input unchanged and malformed input is rejected.
0011
0101
1__0
1__0
R3C2 = 0
solution 1
R3C2 = 1
solution 2Extend the counter carefully
For a binary puzzle SAT model, each cell becomes a Boolean variable, with constraints encoding balance, triples and distinct lines. Utomo and Makarim discuss backtracking and SAT in their 2017 paper Solving a Binary Puzzle. Our implementation is an original line-candidate counter, rather than a reproduction of their code or performance experiments.
Keep the same zero, one and multiple-answer checks when changing representations. A puzzle maker can remove a clue and count again before keeping that deletion. A single-answer counter does not establish human difficulty, however. Our construction guide handles that separate editorial decision.