Hashiwokakero (or short Hashi) is a Japanese logic puzzle, where the aim is to find bridges on a grid of islands with the following rules:
- The number of bridges connected to each island must match the number on that island.
- Bridges can only run horizontally or vertically and cannot cross each other.
- Each bridge connects two islands, and there can be one or two bridges between any pair of islands.
- All islands must be connected in a single network, meaning every island must be reachable from every other island.
The problem was proven to be NP-complete using a reduction of Hamiltonian cycles in unit distance graphs [1]. It has already been encoded as a Integer Programming problem before [2], but the formulation there uses
We start by collecting all possible edges, so any direct orthogonal connection between two islands, in the set
By our definition we know
To encode that the number of bridges connecting to island
This leaves only the most difficult constraint, namely that all islands must be connected. The first trick is to encode the constraint that all bridges are connected instead, which is equivalent since each island is connected to at least one bridge by our previous constraints.
For this we translate the BFS search procedure on edges into the model using the binary variable
Source edges are the edges reachable in zero steps, so we ensure with
Inversily, if an edge
We have thus completed the BFS encoding and can now use solve(file::String)
in the Julia code.
In practice, however, the polynomial size connectivity encoding is slower than the dynamically constructed lazy connectivity constraints presented in [2]. Altough we can obtain a highly efficient Hashiwokakero solver if we combine the based model presented here with lazy connectivity constraints, which is implemented as solveLazy(file::String)
in the Julia code. To demonstrate that, we compare the average runtime of our lazy-solve with the runtime of the CLLV model from [2] on the common dataset they provided.
Method | n = 100 | n = 200 | n = 300 | n = 400 |
---|---|---|---|---|
CLLV | 0.16s | 1.13s | 6.32s | 36.94s |
lazy-solve | <0.01s | 0.04s | 0.12s | 1.48s |
As the table shows, the new model represents a drastic improvement in performance for all instance sizes.
(c) Mia Müßig