This script will generate a random complete non-overlapping fill of a 2N by 2N square with 1x2 and 2x1 dominos and render it using Matplotlib.
The core idea is a randomized backtracking algorithm:
- It finds the first empty cell.
- It randomly decides whether to try placing a horizontal or vertical domino first.
- If a placement is possible, it places the domino (marking the cells with a unique ID) and recursively calls itself for the next empty cell.
- If the recursive call fails (meaning that path leads to a dead end), it "un-places" the domino (backtracks) and tries the other orientation.
- Since a complete tiling of a 2N x 2N grid with 1x2 and 2x1 dominos is always possible, this algorithm is guaranteed to find a solution.
import numpy as np
import matplotlib.pyplot as plt
import random
from itertools import count
from matplotlib.patches import Rectangle
from matplotlib.colors import to_rgb, ListedColormap
def generate_domino_tiling(N):
"""
Generates a random complete domino tiling for an N x N square.
N must be even.
Args:
N (int): The side length of the square grid (must be even).
Returns:
list[list[int]]: A 2D list representing the grid, where each cell
contains the ID of the domino it belongs to.
Returns None if N is odd or an error occurs.
"""
if N % 2 != 0:
print("Error: The grid size (N) must be even for a complete domino tiling.")
return None
grid = [[None for _ in range(N)] for _ in range(N)]
# Use itertools.count to generate unique IDs for each domino
domino_id_counter = count(1)
def find_first_empty_cell():
"""Finds the first empty cell (None) in the grid, scanning row by row."""
for r in range(N):
for c in range(N):
if grid[r][c] is None:
return r, c
return None, None # Grid is full
def solve_tiling():
"""
Recursive backtracking function to fill the grid with dominos.
"""
r, c = find_first_empty_cell()
if r is None: # Grid is completely filled
return True
current_domino_id = next(domino_id_counter)
# Define possible placements for the current empty cell (r, c)
# Each tuple: (cell1_coords, cell2_coords, orientation_type)
possible_placements = []
# Try horizontal placement (1x2)
if c + 1 < N and grid[r][c+1] is None:
possible_placements.append(((r, c), (r, c+1), 'H'))
# Try vertical placement (2x1)
if r + 1 < N and grid[r+1][c] is None:
possible_placements.append(((r, c), (r+1, c), 'V'))
# Randomize the order of trying placements for randomness in tiling
random.shuffle(possible_placements)
for cell1, cell2, orientation in possible_placements:
# Place the domino
grid[cell1[0]][cell1[1]] = current_domino_id
grid[cell2[0]][cell2[1]] = current_domino_id
# Recurse: try to fill the rest of the grid
if solve_tiling():
return True
# Backtrack: if the recursive call failed, un-place the domino
grid[cell1[0]][cell1[1]] = None
grid[cell2[0]][cell2[1]] = None
return False # No valid placement worked for the current cell
if not solve_tiling():
print("Failed to generate a tiling. This should not happen for an even N.")
return None
return grid
def render_tiling(grid):
"""
Renders the given domino tiling using Matplotlib.
Args:
grid (list[list[int]]): The 2D grid representing the tiling.
"""
N = len(grid)
fig, ax = plt.subplots(figsize=(8, 8))
domino_colors = {}
visited_cells = set() # To keep track of cells already rendered as part of a domino
# Generate a set of distinct colors for the dominos
# Approximately N*N/2 dominos in total
num_dominos_expected = (N * N) // 2
# Use a diverse colormap and randomize its application
# 'tab20' or 'Paired' are good for distinct categories
colors_list = []
# If using 'tab20', it only has 20 colors. For larger grids, cycle through.
if num_dominos_expected > 20:
# Create a larger list by cycling through or combining colormaps
cmap = plt.cm.get_cmap('tab20', 20)
for i in range(num_dominos_expected):
colors_list.append(cmap(i % 20)) # Cycle through tab20
else:
cmap = plt.cm.get_cmap('tab20', num_dominos_expected)
for i in range(num_dominos_expected):
colors_list.append(cmap(i))
random.shuffle(colors_list) # Randomize color assignment for visual variation
color_idx = 0
for r in range(N):
for c in range(N):
if (r, c) in visited_cells:
continue # Skip if this cell has already been drawn as part of a domino
domino_id = grid[r][c]
if domino_id is None:
# This should ideally not happen in a complete tiling
print(f"Warning: Cell ({r},{c}) is empty in a supposed complete tiling.")
continue
if domino_id not in domino_colors:
domino_colors[domino_id] = colors_list[color_idx % len(colors_list)]
color_idx += 1
color = domino_colors[domino_id]
# Determine if the domino is horizontal or vertical
is_horizontal = False
# Check the cell to the right
if c + 1 < N and grid[r][c+1] == domino_id:
is_horizontal = True
# No need to check down, if not horizontal, it must be vertical (guaranteed by algorithm)
# Matplotlib's (0,0) is bottom-left. Grid (0,0) is top-left.
# Map grid row `r` to plot y-coordinate `N - (r + 1)`
x_start = c
y_start = N - (r + 1) # This is the y-coord for the bottom edge of cell (r,c)
if is_horizontal:
# Rectangle (x_bottom_left, y_bottom_left, width, height)
rect = Rectangle((x_start, y_start), 2, 1,
facecolor=color, edgecolor='black', linewidth=1.5)
visited_cells.add((r, c))
visited_cells.add((r, c + 1))
else: # Must be vertical
# For vertical domino starting at (r,c), the other half is (r+1,c).
# The bottom-left of the 2x1 domino is (c, N - (r+1) - 1)
rect = Rectangle((x_start, y_start - 1), 1, 2,
facecolor=color, edgecolor='black', linewidth=1.5)
visited_cells.add((r, c))
visited_cells.add((r + 1, c))
ax.add_patch(rect)
# Set up plot limits and aesthetics
ax.set_xlim(0, N)
ax.set_ylim(0, N)
ax.set_aspect('equal') # Ensure squares are square
ax.set_xticks(np.arange(N + 1))
ax.set_yticks(np.arange(N + 1))
ax.set_xticklabels([]) # Hide tick labels
ax.set_yticklabels([])
ax.grid(True, which='major', color='gray', linestyle='-', linewidth=0.7) # Grid lines for cells
plt.title(f"{N}x{N} Domino Tiling")
plt.show()
# --- Main execution ---
if __name__ == "__main__":
# Define 'n' for the 2n x 2n square
n_value = 3 # For a 2n x 2n square, so N_grid will be 6x6
N_grid_size = 2 * n_value
print(f"Generating a random tiling for a {N_grid_size}x{N_grid_size} square...")
tiling_grid = generate_domino_tiling(N_grid_size)
if tiling_grid:
print("Tiling generated successfully. Rendering...")
render_tiling(tiling_grid)
else:
print("Failed to generate tiling.")
How to use the script:
- Save: Save the code as a Python file (e.g.,
domino_tiling.py).
- Install Libraries: If you don't have them, install
numpy and matplotlib:
pip install numpy matplotlib
- Run: Execute the script from your terminal:
python domino_tiling.py
The script will generate a Matplotlib window displaying a unique, randomly generated domino tiling of the 2n by 2n square. You can change the n_value variable to control the size of the square (e.g., n_value = 2 for a 4x4 grid, n_value = 4 for an 8x8 grid, etc.). Remember that N_grid_size must always be even.