Chapter 5
Queens, Tilings, ECO and Polyominoes
This chapter solves placement and tiling problems by means of the backtracking programming technique. Our approach has an educational component in the sense that we aim to code as clean as possible, relying on bitmasking manipulation to balance efficiency drawback due to vanilla implementations. We will tackle the -Queens problem, tilings using pentominoes and parallelogram polyominoes; for what concerns placement problems, we will show an implementation of the ECO methodology in order to enumerate classes of objects that obeys particular symbolic equations.
First of all, we introduce basic bitwise tricks and programming idioms that will be useful for the understanding of the upcoming content, which heavily lies on those techniques for the sake of efficiency:
def is_on(S, j):
return (S & (1 << j)) >> j
def set_all(n):
return (1 << n) - 1
def low_bit(S):
return (S & (-S)).bit_length() - 1
def clear_bit(S, j):
return S & ~(1 << j)>>> S = 0b101010
>>> is_on(S, 3), is_on(S, 2)
(1, 0)
>>> bin(set_all(10))
'0b1111111111'
>>> low_bit(0b100101)
0
>>> low_bit(0b100100)
2
>>> low_bit(1 << 5)
5
>>> S = 0b101010
>>> bin(clear_bit(S, 1))
'0b101000'Uses of bitmasking functions.
Many other techniques can be found in H. S. Warren. Hacker’s Delight. Addison-Wesley Professional, 2nd edition, 2012. ISBN 0321842685, 9780321842688.
5.1The -Queens problem#
The -Queens problem is a well known problem in computer science and it is often used as a “benchmark” to test efficiency of new heuristics and approaches; many resources talks about it, see the survey J. Bell and B. Stevens. A survey of known results and research areas for n-queens. Discrete Mathematics, 309(1):1–31, 2009. ISSN 0012-365X. doi: 10.1016/j.disc.2007.12.043. URL http://www.sciencedirect.com/science/article/pii/S0012365X07010394. In this section we provide a pythonic implementation of an algorithm using the idea described in Chapter of F. Ruskey. Combinatorial Generation. 2003. URL http://www.1stworks.com/ref/RuskeyCombGen.pdf.
We use three bit masks, namely integers, to represent whether a row, a raising and a falling diagonals are under attack by an already placed queen, instead of three boolean arrays. It is sufficient to use one bit only to represent that a cell on a diagonal is under attack, hence to each diagonal is associated one bit according to:
if such diagonal is raising, call it , then
in words, the sum of the row and column indices is constant along raising diagonals. Therefore diagonal is associated to the bit in position of a suitable bitmask ;
otherwise, if such diagonal is falling, call it , then
in words, the difference of the column and row indices is constant along falling diagonals. Therefore diagonal is associated to the bit in position of a suitable bitmask . In order to be consistent, if then take the difference modulo , where is the number of rows (and columns), formally
which entails that
equals
where rows and cols indexes range in ; in both cases, it is necessary a bitmask bits long.
The function queens is a Python generator of solutions for the -Queens problem,
def queens(n):
sol = [0] * n # Initialize the permutation that has
# *columns* indices and *rows* as values.
def gen(c, rows, raises, falls):
for r in range(n): # For each row index:
raising = c + r # when r > c negative positions appear in the
falling = (c - r) % (2*n-1) # *most significant part* of `falling`.
if (is_on(rows, r) # if there is no queen on the same row and on
and is_on(raises, raising) # the same raising and falling diagonals,
and is_on(falls, falling)): # then `r,c` is a candidate position.
sol[c] = r # remember the choice of `r`.
if c == n-1: # if this recursive call concerns the last
yield sol # column then no more work has to be done,
else: # yield a result. Otherwise, recurs looking
yield from gen(c+1, # for a location in the remaining columns,
clear_bit(rows, r), # propagating the fact that row `r` and
clear_bit(raises, raising), # diagonals `raising` and `falling`
clear_bit(falls, falling)) # are under attack and no more selectable.
return gen(0, set_all(n), set_all(2*n-1), set_all(2*n-1)) # start the enumeration of solutions.and it returns all the solution to the given problem when required to do so, as the next example shows.
Example 5.1. Solutions to the -Queens problem are
>>> for s in queens(5):
... print(pretty(s))|Q| | | | | |Q| | | | | | | |Q| | | | | | |Q| | | | | |Q| |
| | | |Q| | | | |Q| | | |Q| | | | | |Q| | | | | | |Q| | | |
| |Q| | | | | | | | |Q| | | | |Q| | | | |Q| | | | | | | |Q|
| | | | |Q| | |Q| | | | | |Q| | | | | | | | |Q| | | |Q| | |
| | |Q| | | | | | |Q| | | | | | |Q| | |Q| | | | |Q| | | | |
| |Q| | | | | | | | |Q| | |Q| | | | | | | | |Q| | | |Q| | |
| | | |Q| | | | |Q| | | | | | | |Q| | |Q| | | | | | | | |Q|
|Q| | | | | |Q| | | | | | | |Q| | | | | | |Q| | | |Q| | | |
| | |Q| | | | | | |Q| | |Q| | | | | |Q| | | | | | | | |Q| |
| | | | |Q| | |Q| | | | | | | |Q| | | | |Q| | | |Q| | | | |In these examples the following pretty printer is used to represent solutions drawing them in bare minimal ASCII,
def pretty(sol):
n = len(sol)
s = ""
for r in range(n):
pos = sol.index(r)
row = "|".join('Q' if c == pos else ' '
for c in range(n))
s += "|{}|\n".format(row)
return sEnumerating all solutions for different integers we get the known sequence http://oeis.org/A000170,
>>> [len(list(queens(i))) for i in range(1,13)]
[1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200]Example 5.2. We tackle the more complex -Queens problem, whose first solution is about seconds away
>>> more_queens = queens(24)
>>> print(pretty(next(more_queens)))|Q| | | | | | | | | | | | | | | | | | | | | | | |
| | | |Q| | | | | | | | | | | | | | | | | | | | |
| |Q| | | | | | | | | | | | | | | | | | | | | | |
| | | | |Q| | | | | | | | | | | | | | | | | | | |
| | |Q| | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | |Q| | | | | | | |
| | | | | | | | | | | | | | | | | | | | | |Q| | |
| | | | | | | | | | | | | | | | | |Q| | | | | | |
| | | | | |Q| | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | |Q| | | | | | | | | |
| | | | | | |Q| | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | |Q| | | | | |
| | | | | | | | | | | | | | | | | | | | |Q| | | |
| | | | | | | |Q| | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | |Q|
| | | | | | | | | | | | | | | | | | | |Q| | | | |
| | | | | | | | | | | | | | | | | | | | | | |Q| |
| | | | | | | | |Q| | | | | | | | | | | | | | | |
| | | | | | | | | | |Q| | | | | | | | | | | | | |
| | | | | | | | | | | | |Q| | | | | | | | | | | |
| | | | | | | | | | | | | | | |Q| | | | | | | | |
| | | | | | | | | |Q| | | | | | | | | | | | | | |
| | | | | | | | | | | |Q| | | | | | | | | | | | |
| | | | | | | | | | | | | |Q| | | | | | | | | | |5.2Polyominoes#
In this section we play with some problems concerning polyominoes, formalized and introduced by prof. Solomon Golomb in S. Golomb. Polyominoes. Princeton University Press, 2nd edition, 1996. ISBN 9780691024448. Our aim is to provide a generic algorithm that consumes a board where it is possible to place some pieces and produces a collection of (possibly incomplete) tilings of the board. Therefore we describe (i) how boards are encoded, (ii) how shapes can be defined and (iii) the fundamental concept of anchor that allows us to bookkeep the next free cell in the board. Our implementation is coded in Python and has an educational flavor; additionally, for more puzzles and problems solved using the same language see D. Goodger. Polyominoes: Puzzles & Solutions, 2015. URL http://puzzler.sourceforge.net, while D. E. Knuth. Dancing links. eprint arXiv:cs/0011047, November 2000 popularize the idea of H. Hitotumatu and K. Noshita. A technique for implementing backtrack algorithms and its application. Information Processing Letters, 8(4):174–175, 1979. ISSN 0020-0190. doi: 10.1016/0020-0190(79)90016-4. URL http://www.sciencedirect.com/science/article/pii/0020019079900164 about a clever use of doubly linked lists to tackle combinatorial enumerations via depth-first searches and backtracking.
5.2.1Boards, shapes, anchors for backtracking#
Maybe the hardest part in the understanding concerns the representations of both the board and the state (free or occupied) of each cell; moreover, the same difficulty arises for shapes and their orientations as well. We answer to each question in turn:
a board with rows and columns is represented by an integer with bits; this is because we want to use bit masking techniques and it is efficient to find the next free cell (using the utility function
low_bit), which correspond to the position of the first bit from the right, namely the right-most in its least significant part. Here it is,a shape is a collection of cells, usually sharing an edge pairwise. We choose to represent a shape as a
namedtupleobject: it has an hashable component and a collection of isomorphisms to represent rotations and mirroring, coded as a lambda expression which consumes the anchor position as a pair of row and column indices, and returns a list of isomorphic shapes, namely positions coding symmetry, reflection or rotation of the shape; therefore, each isomorphism is a sequence of positions too.an anchor is the position in which the top-left cell of a shape orientation will be placed in the next free cell of the board and every orientation should be relative to the anchor provided. The anchor is always given with respect to position
(r,c):* (r-2,c+2) * -> (r-1,c+2) * * * (r,c) (r,c+1) (r, c+2)so the orientation is coded as the tuple
((r,c), (r,c+1), (r-2,c+2), (r-1,c+2), (r, c+2))in the given order, where pairs are listed according to the order top to bottom then left to right, namely when rows are exhausted repeat from to the top of the next column.
In order to structure our thoughts, we start with the definition of the shape
concept as a namedtuple object
from collections import namedtuple
shape_spec = namedtuple('shape_spec', ['name', 'isomorphisms',])that allows us to define the backtracking algorithm
def polyominoes(dim, shapes, availables='ones',
max_depth_reached=None, forbidden=[],
pruning=lambda coord, positions, shapes: False):
rows, cols = dim
sol = []
if not availables or availables == 'ones':
availables = {s.name:1 for s in shapes}
elif availables == 'inf':
availables = {s.name:-1 for s in shapes}
def place(S, positions):
for r, c in positions:
S = clear_bit(S, r + rows*c)
return S
def shapes_available():
return {s for s in shapes if availables[s.name]}
def gen(positions, attempts):
p = low_bit(positions)
c, r = divmod(p, rows)
if pruning((r,c), positions, shapes_available()):
raise StopIteration()
for i, s in enumerate(shapes):
if not availables[s.name]: continue
for j, iso in enumerate(s.isomorphisms(r, c)):
if all(0 <= rr < rows
and 0 <= cc < cols
and is_on(positions, rr + rows*cc)
for rr, cc in iso):
fewer_positions = place(positions, iso)
availables[s.name] -= 1
sol.append((s, positions, (r,c), iso),)
if not (fewer_positions and attempts):
yield sol
else:
yield from gen(fewer_positions, attempts-1)
sol.pop()
availables[s.name] += 1
return gen(place(set_all(rows*cols), forbidden),
max_depth_reached or -1)5.2.2Pentominoes#
We start with a relatively simple set of shapes, those composed of unit
cells and commonly known as pentominoes. According to our encoding,
we introduce shapes with their orientations; for example, here is the
definition of the V_shape:
"""
* * * * * * * *
* * * *
* * * * * * * *
"""
V_shape = shape_spec(
name='V',
isomorphisms=lambda r, c: [
((r,c), (r+1,c), (r+2,c), (r+2, c+1), (r+2, c+2)),
((r,c), (r, c+1), (r,c+2), (r+1, c+2), (r+2, c+2)),
((r,c), (r,c+1), (r-2,c+2), (r-1,c+2), (r, c+2)),
((r,c), (r+1,c), (r+2,c), (r,c+1), (r, c+2))
])>>> for i in range(6):
... print(pretty(next(tilings)))┌─────────────────────┐
│ β δ δ δ ε ε ι ι ι ι │
│ β δ θ δ α ε ε λ λ ι │
│ β θ θ α α α ε η λ λ │
│ β θ γ μ α η η η λ ζ │
│ β θ γ μ μ η κ ζ ζ ζ │
│ γ γ γ μ μ κ κ κ κ ζ │
└─────────────────────┘
┌─────────────────────┐
│ β δ δ δ η η α ζ ζ ζ │
│ β δ θ δ η α α α ζ κ │
│ β θ θ η η λ α ε ζ κ │
│ β θ γ λ λ λ ε ε κ κ │
│ β θ γ ι λ ε ε μ μ κ │
│ γ γ γ ι ι ι ι μ μ μ │
└─────────────────────┘
┌─────────────────────┐
│ β δ δ δ η η ι ι ι ι │
│ β δ θ δ η ε ε λ λ ι │
│ β θ θ η η α ε ε λ λ │
│ β θ γ μ α α α ε λ ζ │
│ β θ γ μ μ α κ ζ ζ ζ │
│ γ γ γ μ μ κ κ κ κ ζ │
└─────────────────────┘
┌─────────────────────┐
│ β ε ε ζ ζ ζ ι ι ι ι │
│ β κ ε ε ζ λ θ θ θ ι │
│ β κ κ ε ζ λ λ λ θ θ │
│ β κ γ δ δ α λ η η μ │
│ β κ γ δ α α α η μ μ │
│ γ γ γ δ δ α η η μ μ │
└─────────────────────┘
┌─────────────────────┐
│ β ε ε ζ ζ ζ ι ι ι ι │
│ β κ ε ε ζ λ θ θ θ ι │
│ β κ κ ε ζ λ λ λ θ θ │
│ β κ γ μ η η λ α δ δ │
│ β κ γ μ μ η α α α δ │
│ γ γ γ μ μ η η α δ δ │
└─────────────────────┘
┌─────────────────────┐
│ β ε ε μ μ μ ζ δ δ δ │
│ β κ ε ε μ μ ζ δ θ δ │
│ β κ κ ε α ζ ζ ζ θ θ │
│ β κ γ α α α λ η η θ │
│ β κ γ ι α λ λ λ η θ │
│ γ γ γ ι ι ι ι λ η η │
└─────────────────────┘The first tilings enumerated by generator polyominoes using the shapes collection of pieces.
With the current setup we can define the complete set of shapes and, consequently, the generator over the solution space for the tilings of a board having piece of each shape, respectively.
>>> '''
... X: I: V: U: W: T:
... * * * * * * * * *
... * * * * * * * * *
... * * * * * * * * * *
... *
... *
...
... Z: N: L: Y: F: P:
... * * * * * *
... * * * * * * * * * * * * *
... * * * * * * *
... * * * *
... '''
>>> shapes = [X_shape, I_shape, V_shape, U_shape, W_shape, T_shape,
... Z_shape, N_shape, L_shape, Y_shape, F_shape, P_shape]
>>> dim = (6,10)
>>> tilings = polyominoes(dim, shapes, availables="ones")In the margin we report an application of our implementation; in particular, it shows our choice to represent tilings, drawing shapes as collections of multiple occurrences of the same greek letters.
With forbidden cells and limited shapes availability#
It is possible to tailor the enumeration with respect to (i) the number of
available pieces for each shape and to (ii) forbidden placements on the board.
Both of them can be easy achieved by tuning the application of polyominoes
providing the keyword arguments availables and
forbidden, respectively. For the former, provide a dictionary of
(k, v) objects, where k denotes the shape’s name and v
denotes its pieces availability; for the latter, provide a list of
positions that should be avoided in the placement process. An example follows,
>>> dim = (6,10)
>>> tilings = polyominoes(
... dim, shapes,
... availables={s.name:3 for s in shapes},
... forbidden=[(0,0), (1,0), (2,0), (3,0), (4,0),
... (1,9), (2,9), (3,9), (4,9), (5,9),
... (1,5), (2,4), (2,5), (3,4), (3,5)])and some tilings are shown in the margin.
>>> for i in range(6):
... print(pretty(next(tilings)))┌─────────────────────┐
│ γ γ γ δ δ δ ζ ζ ζ │
│ ι ι γ δ δ λ ζ │
│ ι μ γ λ λ ζ │
│ ι μ μ η λ λ │
│ ι μ μ θ θ η η η │
│ β β β β β θ θ θ η │
└─────────────────────┘
┌─────────────────────┐
│ γ γ γ ι ι ι ι λ λ │
│ μ μ γ ι ε λ λ │
│ μ μ γ ε ε λ │
│ δ μ δ η ε ε │
│ δ δ δ θ θ η η η │
│ β β β β β θ θ θ η │
└─────────────────────┘
┌─────────────────────┐
│ γ γ γ ι ι ι ι λ λ │
│ γ μ μ ι ε λ λ │
│ γ μ μ ε ε λ │
│ δ μ δ η ε ε │
│ δ δ δ θ θ η η η │
│ β β β β β θ θ θ η │
└─────────────────────┘
┌─────────────────────┐
│ γ γ γ θ θ δ δ λ λ │
│ γ θ θ θ δ λ λ │
│ γ ε ε δ δ λ │
│ ε ε κ ζ μ μ │
│ ε κ κ κ κ ζ μ μ │
│ β β β β β ζ ζ ζ μ │
└─────────────────────┘
┌─────────────────────┐
│ γ γ γ θ θ δ δ λ λ │
│ γ θ θ θ δ λ λ │
│ γ ε ε δ δ λ │
│ ε ε κ η η μ │
│ ε κ κ κ κ η μ μ │
│ β β β β β η η μ μ │
└─────────────────────┘
┌─────────────────────┐
│ γ γ γ θ θ δ δ λ λ │
│ γ θ θ θ δ λ λ │
│ γ ε ε δ δ λ │
│ ε ε κ μ μ μ │
│ ε κ κ κ κ μ μ ι │
│ β β β β β ι ι ι ι │
└─────────────────────┘The first tilings enumerated by generator polyominoes using the shapes collection of pieces under the restriction to have pieces for each shape and forbidden cells should be left blank.
5.2.3Polyomino’s order#
In the exercise 7 of his book, Ruskey asks to find the order of some polyomino, defined according to
Definition 5.3 (Order of a polyomino). The order of a polyomino is the smallest number of copies that will perfectly fit into a rectangle board, where rotations and reflections of are allowed.
We take into account the Y polyomino and we check that its order is
actually in tiling a board ; in order to show this fact, we
give copies of the Y_shape object, each one with one piece
available, respectively; although there are many other solutions,
>>> Y_shapes = [
... shape_spec(name="{}_{}".format(Y_shape.name, i),
... isomorphisms=Y_shape.isomorphisms)
... for i in range(10)
... ]
>>> dim = (5,10)
>>> Y_tilings = polyominoes(dim, Y_shapes, availables='ones')
>>> print(pretty(next(Y_tilings)))┌─────────────────────┐
│ α γ γ γ γ ζ ι ι ι ι │
│ α α δ γ ζ ζ ζ ζ ι κ │
│ α δ δ δ δ η η η η κ │
│ α β ε ε ε ε θ η κ κ │
│ β β β β ε θ θ θ θ κ │
└─────────────────────┘the one shown above solves the problem.
5.2.4Fibonacci’s tilings#
In this section we take into account a smaller set of shapes, composed of squares and dominos pieces, in order to tile boards with an increasing number of rows; eventually, enumerations of tilings for greater boards are counted by known sequences in the OEIS.
"""
*
"""
square_shape = shape_spec(
name='square',
isomorphisms=lambda r, c: [((r, c),)])
"""
* * *
*
"""
domino_shape = shape_spec(
name='domino',
isomorphisms=lambda r, c: [ ((r, c), (r, c+1)),
((r, c), (r+1, c))])
fibonacci_shapes = [square_shape, domino_shape]Tiling greater boards, ascending ordered according to the number of rows, we enumerate the sequences
>>> [ [len(list(polyominoes(dim=(j,i),
... shapes=fibonacci_shapes,
... availables='inf')))
... for i in range(n)]
... for j, n in [(1, 13), # https://oeis.org/A000045
... (2, 13), # https://oeis.org/A030186
... (3, 7), # https://oeis.org/A033506
... (4, 7), # https://oeis.org/A033507
... (5, 6)]] # https://oeis.org/A033508
[[0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233],
[0, 2, 7, 22, 71, 228, 733, 2356, 7573, 24342, 78243, 251498, 808395],
[0, 3, 22, 131, 823, 5096, 31687],
[0, 5, 71, 823, 10012, 120465, 1453535],
[0, 8, 228, 5096, 120465, 2810694]]which counts Fibonacci’s numbers, the number of matchings in graphs , , and , respectively. For the sake of clarity, the ways to tile a simple board are:
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ α α α α α α │ │ α α α α β β │ │ α α α β β α │ │ α α β β α α │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ α α β β β β │ │ α β β α α α │ │ β β α α α α │ │ β β α α β β │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ α β β α β β │ │ α β β β β α │ │ β β α β β α │ │ β β β β α α │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
┌─────────────┐
│ β β β β β β │
└─────────────┘5.3Parallelogram Polyominoes#
In this section we study a collection of polyominoes where their shapes are subject to a constraint; precisely, a parallelogram polyomino is defined by two paths that only intersect at their origin and extremity, composed of East and South steps only. They are counted by Catalan numbers according to their semiperimeter, which equals the sum of their heights and widths; for the sake of clarity, both M.-P. Delest and J.-M. Fedou. Enumeration of skew Ferrers diagrams. Discrete Mathematics, 112(1-3):65–79, North-Holland, 1993 and M. Delest, D. Gouyou-Beauchamps, and B. Vauquelin. Enumeration of parallelogram polyominoes with given bond and site perimeter. Graphs and Combinatorics, 3:325–339, January 1987 are extensive studies.
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢
▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢
▢ ▢ ▢
▢Parallelogram Polyominoes with semiperimeter , which are in total, the th Catalan number.
Example 5.4. The set of parallelogram polyominoes shown above can be used to tile a board ;
precisely, using the enumerator polyominoes again, we show the first
incomplete and the first complete tilings,
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
| | | |_ |_ _ _ _ _| |● | | | |_ | |_ |_ _ |
| | | |_ | | | | | | | | |_ | |_ _ _|_ _|
|_ _ _| | | |_|_ | | |_ | |_ _ _| | | |_|_ _ _|_ _ _ |
| |_ _|_ _|_ | |_ | | |_| | |_ _|_ _|_ | | |_ |_|
|_ | | |_ _|_| |_| | |● |_ | | |_ _| | | | |
| |_ _|_ _ |_ |_ |_ |_| | | |_ _|_ _ |_ | | |_ | | |_ _|
| | |_| |_ _|_ _ _|_ _|_ _| | | |_| | | |_ |_| | |_ |
|_ _ _|_ _ | |_ |_ |_ | |● |_ _ _|_ _ | |_|_ |_ _|_|_ _| |
| |_ |_|_ _ _|_ | | |_ | | |_ |_|_ _ _|_| |_ | | |
| | | |_ |_|_ _|_ _| | | | | |_ |_ | |_ |_|
|_ _ _|_ _|_ _ _ _|_ _ _|_ | |_| |_ _ _|_ _|_ _ _ _|_ | |_ _|_ _|
| |_ | |_ _ | | |● | |_ | |_|_| |_ _ |
|_ _ _ _| |_ _ _|_ _ _ _| | | |● |_ _ _ _| |_ _ _|_ _ _ _| | | |
| | |_ _ |_ _ _ | |_|_|_ _| | | |_ _ |_ _ _ _ _|_ | |_|
| |_ | |_|_ _ |_| |_ _ | | |_ | |_|_ _ |_ |_| |
|_ _ _|_ _|_ _ _ _|_ _|_ _ _|_ _| |_ _ _|_ _|_ _ _ _|_ _|_ _ _|_ _|respectively. The solution space of this problem is very sparse and the enumeration is pretty hard; despite the vanilla approach used, our implementation allows us to provide an heuristic function (to prune any attempt to insert a polyomino on last row or last column, for example) but we get no gain in efficiency. On the contrary, we note that the order in which polyominoes are chosen for placement leverage the execution time, even for smaller boards; however, for greater boards the problem remains open.
5.4An implementation of the ECO method#
The ECO methodology is introduced in E. Barcucci, A. Del Lungo, E. Pergola, and R. Pinzani. A methodology for plane tree enumeration. Discrete Mathematics, 180(1):45–64, 1998b. ISSN 0012-365X. doi: 10.1016/S0012-365X(97)00122-2. URL http://www.sciencedirect.com/science/article/pii/S0012365X97001222. Proceedings of the 7th Conference on Formal Power Series and Algebraic Combinatorics and refined in E. Barcucci, A. Del Lungo, E. Pergola, and R. Pinzani. ECO:a methodology for the enumeration of combinatorial objects. Journal of Difference Equations and Applications, 5(4-5):435–490, Taylor & Francis, 1999. doi: 10.1080/10236199908808200 in order to enumerate classes of combinatorial objects; relying on the idea to perform local expansion on objects’ active sites by means of an operator, the ECO method gives a recursive construction of the class that objects belong to.
In the spirit of A. Bernini, I. Fanti, and E. Grazzini. An exhaustive generation algorithm for Catalan objects and others. 2007 and S. Bacchelli, E. Barcucci, E. Grazzini, and E. Pergola. Exhaustive generation of combinatorial objects by ECO. Acta Informatica, 40(8):585–602, July 2004. ISSN 1432-0525. doi: 10.1007/s00236-004-0139-x, we provide a implementation of the ECO method which allows us to build classes of combinatorial objects; consequently, enumeration comes for free. Moreover, defining a recursive shape as the combination of symbols denoting the objects’ structure with symbols denoting the objects’ active sites, namely positions where it is possible to perform a local expansion, we have a data structure to be manipulated by a Python function, which reifies the operator concept.
For the sake of clarity, let ★ be an active site that accepts
to be replaced by
●
★ ★hence, operator → performs replacements for each site; for example,
● ● ● ●
● ★ → ● ★ ● ★ ● ●
★ ★ ● ★ ● ★ ★
★ ★ ★ ★In order to understand how → works, we label each ★ with
a integer subscript that denotes the discrete time in which it will be
replaced,
● ● ● ●
● ★₃ → ● ★₃ ● ★₃ ● ●
★₁★₂ ● ★₂ ● ★₄★₅
★₄★₅ ★₄★₅and we normalize discrete times of produced objects in order to restart the
application of operator → to each one of them,
● ● ●
● ★₂ ● ★₁ ● ●
● ★₁ ● ★₁★₂
★₃★₄ ★₂★₃From this characterization it is possible to recover the correlated concepts of
generating tree and succession rule F.R.K. Chung, R.L. Graham, V.E. Hoggatt, and M. Kleiman. The number of baxter permutations. Journal of Combinatorial Theory, Series A, 24(3):382–394, 1978. ISSN 0097-3165. doi: 10.1016/0097-3165(78)90068-7. URL http://www.sciencedirect.com/science/article/pii/0097316578900687.
The former is straightforward encoded within the application of the operator
→, the latter is because (i) on the left
hand side of → there are object with active sites and (ii) on
the right hand side of → there are objects with and
active sites, respectively.
In the following examples we apply this methodology to build and enumerate known classes of combinatorial objects.
Example 5.5 (Binary trees). Their class is encoded by
binary_tree_shapes = {
'bintree': lambda r, c: Anchor(symbol='●', stars=[
Star(row=r+1, col=c-1, offsets=None,
link='bintree', symbol='★'),
Star(row=r+1, col=c+1, offsets=None,
link='bintree', symbol='★'),
]),
}and enumerated as shown in the margin.
According to the symbolic equation
★ = ●
★ ★symbol ★ enumerates the (i) generation
●
★ ★the (ii) generation
● ●
● ★ ●
★ ★ ★ ★the (iii) generation
● ● ● ● ●
● ★ ● ★ ● ● ● ●
● ★ ● ★ ★ ● ★ ●
★ ★ ★ ★ ★ ★ ★ ★the (iv) generation
● ● ● ●
● ★ ● ★ ● ★ ● ●
● ★ ● ★ ● ● ● ★ ★
● ★ ● ★ ★
★ ★ ★ ★
● ● ● ●
● ★ ● ● ● ● ●
● ☆ ★ ● ● ★
● ★ ★ ● ★ ★
★ ★ ★ ★
● ● ● ●
● ● ● ● ●
● ● ★ ● ★ ● ●
★ ★ ● ★ ● ★ ★
★ ★ ★ ★
● ●
● ●
● ●
● ★ ●
★ ★ ★ ★where the symbol ☆ means the superposition of symbols ● and
★ in back and fore ground, respectively.
Enumerations up to the th generation of binary trees.
The previous example shows our way to encode the recursive shape of binary
trees; in particular, shapes are vanilla Python dictionaries, where each one of
them contains key-value pairs (k, v) where k denotes the shape
label and v denotes a function that consumes a coordinate (r,c)
and produces an Anchor object that carries information about the
structure symbol and the collection of shape’s active sites.
Example 5.6 (Dyck paths). Their class is encoded by
dyck_path_shapes = {
'dick': lambda r, c: Anchor(symbol='/', stars=[
Star(row=r-1, col=c+1, offsets=(0, 2),
link='dick', symbol='★'),
Star(row=r, col=c+2, offsets=None,
link='dick', symbol='★'),
]),
}and enumerated as shown in the margin.
According to the symbolic equation
★
★ = / ★symbol ★ enumerates the (i) generation
★
/ ★the (ii) generation
★
/ ★ ★
/ ★ / / ★the (iii) generation
★
/ ★ ★
/ ★ / / ★ / ★
/ ★ / ★ / / ★
★
/ ★ ★
/ / ★ / / / ★the (iv) generation
★
/ ★ ★
/ ★ / / ★ / ★
/ ★ / ★ / / ★
/ ★ / ★ / ★
★
/ / ★ ★
/ ★ / / ★ / / / ★
/ / ★ / ★ / ★
★
/ / ★ / / ★ / ★
/ / ★ / / ★ / / / ★
★
/ ★ ★
/ ★ / / ★ / ★
/ / ★ / / ★ / / / ★
★
/ ★ ★
/ / / ★ / / / / ★Enumerations up to the th generation of Dyck paths.
Previous example spots a feature provided by Star objects,
namely the capability to shift part of the structure in order to make
room for local expansions; this is achieved by the keyword argument
offset, which has to be a pair (or, oc) where components
are integers that denote row and column offsets, respectively.
For the Dyck paths shape, we provide offset=(0,2) for the topmost
active site because when the structure is expanded there, the rightmost
path already generated should be shifted by columns while remaining
at the same distance from the axis.
Example 5.7 (Balanced Parens). Their class is encoded by
balanced_parens_shapes = {
'parens': lambda r, c: Anchor(symbol='(', stars=[
Star(row=r, col=c+1, offsets=(0, 3),
link='parens', symbol='★'),
Star(row=r, col=c+3, offsets=None,
link='parens', symbol='★'),
]),
}and enumerated as shown in the margin.
Both the previous examples and the next one enumerate classes of objects counted by Catalan numbers and each class obeys to the succession rule and , where .
According to the symbolic equation
★ = (★)★symbol ★ enumerates the (i) generation
(★ ★the (ii) generation
((★ ★ ★
( (★ ★the (iii) generation
(((★ ★ ★ ★
(( (★ ★ ★
(( (★ ★
( ((★ ★ ★
( ( (★ ★the (iv) generation
((((★ ★ ★ ★ ★
((( (★ ★ ★ ★
((( (★ ★ ★
((( (★ ★
(( ((★ ★ ★ ★
(( ( (★ ★ ★
(( ( (★ ★
(( ((★ ★ ★
(( ( (★ ★
( (((★ ★ ★ ★
( (( (★ ★ ★
( (( (★ ★
( ( ((★ ★ ★
( ( ( (★ ★Enumerations up to the th generation of balanced parens.
Example 5.8 (Steep parallelograms polyominoes). They are a refinement of parallelogram polyominoes because the lower border of those polyominoes has no pair of consecutive horizontal steps. Their class is encoded by
steep_shapes = {
'one_star': lambda r, c: Anchor(symbol='▢', stars=[
Star(row=r-1, col=c, offsets=None,
link='two_stars', symbol='☆'),
]),
'two_stars': lambda r, c: Anchor(symbol='▢', stars=[
Star(row=r-1, col=c, offsets=None,
link='two_stars', symbol='☆'),
Star(row=r, col=c+1, offsets=None,
link='one_star', symbol='★'),
]),
}and enumerated as shown in the margin.
According to the mutually symbolic equations
☆ ☆
★ = ▢ ☆ = ▢ ★symbol ★ enumerates the (i) generation
☆
▢the (ii) generation
☆
▢ ★
▢the (iii) generation
☆
▢ ★ ☆
▢ ★ ▢ ▢
▢ ▢the (iv) generation
☆
▢ ★ ☆ ☆
▢ ★ ▢ ▢ ▢ ☆ ▢ ★
▢ ★ ▢ ★ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢
☆
▢ ★ ☆
▢ ★ ▢ ▢ ▢ ☆ ▢
▢ ★ ▢ ★ ▢ ▢ ▢ ☆
▢ ★ ▢ ★ ▢ ★ ▢ ▢
▢ ▢ ▢ ▢
☆ ☆
▢ ★ ☆ ▢ ★
▢ ▢ ▢ ◐ ▢ ▢ ★ ▢ ★
▢ ★ ▢ ▢ ▢ ▢ ▢ ▢
▢ ▢ ▢ ▢
☆
▢ ▢
▢ ▢
▢where the symbol ◐ means the superposition of symbols ▢ and
☆ in back and fore ground, respectively.
Enumerations up to the th generation of steep parallelograms.
In E. Barcucci, A. Del Lungo, J.M. Fédou, and R. Pinzani". Steep polyominoes, -Motzkin numbers and -Bessel functions. Discrete Mathematics, 189(1):21–42, 1998a. ISSN 0012-365X. doi: 10.1016/S0012-365X(97)00275-6. URL http://www.sciencedirect.com/science/article/pii/S0012365X97002756 it is proved that steep parallelogram polyominoes are counted by the Motzkin numbers, in particular the set of those polyominoes having semiperimeter has objects – the -th Motzkin number. Moreover, the enumeration verifies that steep parallelogram polyominoes obey the succession rule and , where .
Example 5.9 (Rabbits). These shapes encode that (i) a couple of young rabbits
○ gets old and becomes ● which, in turn, (ii) gives birth to a
couple of young rabbits and gets older.
rabbits_shapes = {
'young': lambda r, c: Anchor(symbol='○', stars=[
Star(row=r-1, col=c+1, offsets=None,
link='senior', symbol='★'),
]),
'senior': lambda r, c: Anchor(symbol='●', stars=[
Star(row=r, col=c+1, offsets=None,
link='young', symbol='▲'),
Star(row=r+1, col=c+1, offsets=None,
link='senior', symbol='★'),
]),
}The complete enumeration contains doubles, so we report the set of those structures that is actually counted by the Fibonacci numbers; according to the mutually symbolic equations,
★
☆ = ○ ★ = ●☆
★the enumeration process starts with ☆ and enumerates the (i), (ii),
(iii) and (iv) generations
| | ★ | ●☆
★ | ●☆ | ●○ ● | ●○ ★ ● ★ ●
○ | ○ ★ | ○ ★ ○ ●☆ | ○ ○ ●○ ○ ●
| | ★ | ★ ●☆
| | | ★and, finally, the (v) generation
★
●○ ●
●○ ★ ●○ ●☆ ● ●☆ ● ●
○ ○ ★ ○ ●○ ★ ○ ● ★ ○ ●
●○ ●
★ ●☆
★as required.
Conclusions#
This chapter has presented an extensive exercise in coding, practicing with backtracking programming techniques; in particular, vanilla implementations pair with bitmasking techniques to speed up computation, keeping elegance and clarity at the same time.
We strive to write generic algorithms that work in different contexts ranging from the placement problems, such as the -Queens problem, to tiling problems using different shapes; moreover, the same minimal and open approach allows us to tackle enumeration tasks starting from simple but powerful specifications of classes of combinatorial objects and a well known enumeration method called ECO has been fully implemented.