GitHub
6 min read
  • Algorithms
  • AI
  • Python

LITS (ヌルオミノ) Solver

Nikoli's tetromino puzzle as a constraint satisfaction problem.

Table of contents
  1. The puzzle
  2. Try it
  3. How the solver works
    1. The problem, formally
    2. Every placement, up front
    3. What a state holds
    4. Checking a move
    5. Placing a piece
    6. Which region goes next
    7. Depth-first search
    8. Keeping everything connected
  4. See it run

LITS, formerly known as Nuruomino (ヌルオミノ), is a binary determination puzzle published by Nikoli: the grid is cut into regions, and every region must hold exactly one tetromino. Below are the rules, a board to play on, and how the solver we built for our Artificial Intelligence class tackles this NP-hard problem.Sidenote:At least as hard as every problem in NP, so no known algorithm solves every puzzle quickly. Deciding whether a LITS grid has a solution is NP-complete, as Biro and Schmidt proved (EuroCG 2017).

The puzzle

Shade exactly four connected cells in every region so that each region holds one tetromino. Pieces may be rotated and flipped, so there are only four shapesSidenote:There is no O piece. The square tetromino is itself a filled 2×2 block, so it would break rule 3 below wherever it went.: L I T S. A finished board must obey three more rules.

L

8 of 8 kept

I

2 of 8 kept

T

4 of 8 kept

S

4 of 8 kept

  1. No identical shapes touching

    Two pieces of the same shape may not share an edge. Different shapes may.

    broken
    valid
  2. Everything is connected

    All shaded cells form one group, joined by edges (corners do not count).

    broken
    valid
  3. No 2×2 blocks

    Four shaded cells may never form a square.

    broken
    valid

Try it

Click or drag to shade cellsSidenote:A piece becomes coloured once its four cells form a valid shape; until then its cells stay grey.; use Mark (or right-click) to note cells you know are empty. You get three hints, refilled when you start over. If you get stuck, Solve picks up where you left off and finishes the board: it keeps your pieces where they can be part of a solution and explains any it has to remove, and you see every attempt, dead end and backtrack it makes. Use Step and Back to move through it one attempt at a time.

12345
Your move. Shade four connected cells in a region. Small, cramped regions have the fewest ways to fit a piece, so they are the best place to start.

Rules check

  • waiting for Python…

Board

Solver

Load a puzzle

One row per line, cell values separated by spaces or tabs. Cells with the same number form a region. The grid must be square.

How the solver works

The solver generates every possible placement once, then searches depth-first, checking each move against the rules and pruning the neighbouring regions’ options as it goes. The code below is excerpted from our repository on GitHub.

The problem, formally

As a constraint satisfaction problem, LITS is a triple ⟨X,D,C⟩\langle X, D, C \rangle. Number the regions R={1,…,n}R = \{1, \dots, n\}. A placement pp is one of the four tetrominoes L, I, T, S in one orientation at one position on the grid: it covers a set of cells C(p)C(p) and has a shape s(p)∈{L,I,T,S}s(p) \in \{\mathrm{L}, \mathrm{I}, \mathrm{T}, \mathrm{S}\}. Two sets of cells are adjacent, A∼BA \sim B, when a cell of AA shares an edge with a cell of BB.

Variables, one per region:

X={ Xr∣r∈R }X = \{\, X_r \mid r \in R \,\}

Domains, the placements that fit inside each region:

D(Xr)=Pr={ p∣C(p)⊆cells(r) }D(X_r) = P_r = \{\, p \mid C(p) \subseteq \text{cells}(r) \,\}

Constraints, one per rule:

s(Xr)=s(Xr′)  ⇒  ¬ (C(Xr)∼C(Xr′))∀ r≠r′(rule 1)s(X_r) = s(X_{r'}) \;\Rightarrow\; \neg\, \big( C(X_r) \sim C(X_{r'}) \big) \qquad \forall\, r \neq r' \qquad \text{(rule 1)}
⋃r∈RC(Xr)  is edge-connected(rule 2)\textstyle\bigcup_{r \in R} C(X_r) \ \text{ is edge-connected} \qquad \text{(rule 2)}
∣ W∩⋃r∈RC(Xr) ∣≤3for every 2×2 window W(rule 3)\Big|\, W \cap \textstyle\bigcup_{r \in R} C(X_r) \,\Big| \le 3 \qquad \text{for every } 2 \times 2 \text{ window } W \qquad \text{(rule 3)}

Each variable takes exactly one value, so “one tetromino per region” needs no constraint of its own. Rules 1 and 3 are local (rule 1 relates two neighbouring regions, rule 3 at most the four regions under a window); rule 2 is a global constraint over all of them.

Every placement, up front

An action places one tetromino in one region. The distinct orientations of the four shapes come from get_all_orientations.Sidenote:These are the 18 kept versions you saw in the rules: 8 for L, 2 for I, 4 for T and 4 for S. _generate_all_actions slides every orientation over every position of the grid and keeps it for a region when Action.is_valid agrees: all four cells lie inside that region (tetromino_fits_in_region) and the piece shares at least one edge with another region (num_shared_edges). A piece touching no other region could never connect to the rest, so it is dropped before the search even starts.

nuruomino.py
def _generate_all_actions(self, adjacency_graph):
    """Generate all valid actions for each region."""
    all_actions = {}
    regions = adjacency_graph.keys()
    for region in regions:
        all_actions[region] = []
        for tetromino in self._orientations:
            tetromino_array = tetromino.get()
            shape_rows, shape_cols = tetromino_array.shape
            for row in range(self.og_board.size - shape_rows + 1):
                for col in range(self.og_board.size - shape_cols + 1):
                    cells = [(row + row_offset, col + col_offset)
                        for row_offset, col_offset in zip(*np.where(tetromino_array))]
                    action = Action(region, tetromino, cells)
                    if action.is_valid(self.og_board):
                        all_actions[region].append(action)
    return all_actions
nuruomino.py
def is_valid(self, board: Board) -> bool:
    """Returns whether a action is valid or not."""
    return board.tetromino_fits_in_region(self) and
        board.num_shared_edges(self) > 0

What a state holds

A search state (NuruominoState) holds four things. The board is the grid of region ids, with a letter written over each placed piece. filled_regions is the set of regions that already have a piece. adjacency_graph maps each region to the set of regions it touches. actions_graph maps each region to the placements that are still legal for it, which is that region’s remaining domain. The search never edits a state: each move builds a new one, so an older state is always there to go back to.

Checking a move

Before a placement can stay in a region’s list, is_currently_valid tests it against the board as it is now. Each test is one rule from the top of the page: the piece must not overlap a filled cell (tetromino_fits_in_region), must not touch a piece of the same shape (_touches_same_tetromino_shape, rule 1), must still be able to connect when all its neighbours are already filled (_connected_to_other_tetromino_shape, rule 2), and must not complete a 2×2 block (_creates_filled_2x2_region, rule 3). The first failed test rejects it.

nuruomino.py
def is_currently_valid(self, board: Board, filled_regions, adjacency_graph) -> bool:
    """Check if action doesn't overlap already filled cells, doesn't
    create 2x2 filled cells and doesn't touch pieces with the same shape."""
    if not board.tetromino_fits_in_region(self):
        return False
    if self._touches_same_tetromino_shape(board):
        return False
    if not self._connected_to_other_tetromino_shape(board, filled_regions, adjacency_graph):
        return False
    if self._creates_filled_2x2_region(board):
        return False
    return True
nuruomino.py
def _touches_same_tetromino_shape(self, board: Board) -> bool:
    """Check if tetromino touches other tetronimo pieces with the same shape."""
    board_array = board.board
    shape = self.tetromino.shape
    for row, col in self.position:
        if row > 0 and board_array[row-1, col] == shape:
            return True
        if row < board.size - 1 and board_array[row+1, col] == shape:
            return True
        if col > 0 and board_array[row, col-1] == shape:
            return True
        if col < board.size - 1 and board_array[row, col+1] == shape:
            return True
    return False
nuruomino.py
def _creates_filled_2x2_region(self, board: Board) -> bool:
    """Check if placing this tetromino would create
    any 2x2 filled areas, without modifying the board."""
    board_array = board.board
    tetromino_shapes = set(Tetromino.TETROMINO_SHAPES.keys())
    positions = set(self.position)
    potencial_2x2_block = set()
    for row, col in self.position:
        for row_offset in (0, -1):
            for col_offset in (0, -1):
                i, j = row + row_offset, col + col_offset
                if 0 <= i < board.size - 1 and 0 <= j < board.size - 1:
                    potencial_2x2_block.add((i, j))

    for row, col in potencial_2x2_block:
        if (
            ((board_array[row, col] in tetromino_shapes) or ((row, col) in positions)) and
            ((board_array[row + 1, col] in tetromino_shapes) or ((row + 1, col) in positions)) and
            ((board_array[row, col + 1] in tetromino_shapes) or ((row, col + 1) in positions)) and
            ((board_array[row + 1, col + 1] in tetromino_shapes) or ((row + 1, col + 1) in positions))
        ):
            return True
    return False
nuruomino.py
def _connected_to_other_tetromino_shape(self, board: Board, filled_regions,
    adjacency_graph) -> bool:
    """When all adjacent regions are filled the tetromino placed on the
    region needs to touch a tetromino from one of the adjacent regions."""
    adjacent_regions = adjacency_graph.get(self.region, set())
    if not filled_regions.issuperset(adjacent_regions):
        return True
    tetromino_shapes = Tetromino.TETROMINO_SHAPES
    for row, col in self.position:
        if row > 0 and board.board[row - 1, col] in tetromino_shapes:
            return True
        if row < board.size - 1 and board.board[row + 1, col] in tetromino_shapes:
            return True
        if col > 0 and board.board[row, col - 1] in tetromino_shapes:
            return True
        if col < board.size - 1 and board.board[row, col + 1] in tetromino_shapes:
            return True
    return False

Placing a piece

result copies the state (so the parent stays intact for backtracking), writes the piece onto the copied board, and then re-validates the candidate lists of the neighbouring regions with is_currently_valid. Candidates that would overlap, touch an identical shape, complete a 2×2 block or could no longer connect are dropped. If a neighbour ends up with an empty list, the new state is already doomed and the next call to actions will return nothing, so the failure is noticed one step later instead of deep in the subtree.

nuruomino.py
def result(self, state, action):
    """Return the state that results from executing the given action."""
    new_state = NuruominoState(
        board=state.board.copy(),
        actions_graph=state.actions_graph.copy(),
        adjacency_graph={key: value.copy()
            for key, value in state.adjacency_graph.items()},
        filled_regions=state.filled_regions.copy()
    )
    # Update baord.
    new_state.board.run_action(action)
    # Update filled regions.
    new_state.filled_regions.add(action.region)
    # Update adjacency graph.
    new_adjacent_regions = new_state.board.get_adjacent_regions(
        action.position, self.og_board, new_state.filled_regions)
    new_state.adjacency_graph[action.region] = new_adjacent_regions.copy()
    for neighbour in new_adjacent_regions:
        if neighbour in new_state.adjacency_graph:
            new_state.adjacency_graph[neighbour].add(action.region)
    for region, neighbours in new_state.adjacency_graph.items():
        if (region != action.region and action.region in neighbours
            and region not in new_adjacent_regions):
            neighbours.discard(action.region)
    # Update actions graph.
    new_state.actions_graph[action.region] = []
    for region in new_adjacent_regions:
        if region in new_state.actions_graph:
            valid_actions = []
            for new_actions in new_state.actions_graph[region]:
                if new_actions.is_currently_valid(new_state.board,
                    new_state.filled_regions, self.adjacency_graph):
                    valid_actions.append(new_actions)
            new_state.actions_graph[region] = valid_actions
    return new_state

Which region goes next

Each node expands one region only: the unfilled region with the fewest legal placements left. This is the minimum remaining values (fail-first) heuristic. It is safe because every region must receive a piece anyway, so the order cannot change which solutions exist, only how early dead ends show up. A region with zero placements makes the node a dead end immediately.

nuruomino.py
def actions(self, state):
    """Return the actions available in the current state."""
    if not self._adjacency_graph_connected(state.adjacency_graph):
        return []
    return state.actions_graph.get(self._select_next_region(state), [])
nuruomino.py
def _select_next_region(self, state):
    """Selects the next region to explore and test actions."""
    regions = set(state.adjacency_graph.keys())
    regions -= state.filled_regions
    min_actions = min(len(state.actions_graph.get(region, []))
        for region in regions)
    min_regions = [region for region in regions
        if len(state.actions_graph.get(region, [])) == min_actions]

    if len(min_regions) == 0:
        return []
    if len(min_regions) == 1:
        return min_regions[0]
    return max(min_regions, key=lambda region:
        len(state.actions_graph.get(region, [])), default=None)

depth_first_tree_search keeps a frontier, a Python list used as a stack. It pops the newest node, tests it, and pushes all its children. Because children go on top, the search dives into the most recent choice first. There is no separate “undo”: when a branch dies, the next pop() simply returns to the most recent unexplored sibling, which is backtracking. No visited set is needed: each node branches on a single region, so sibling subtrees differ in that region’s piece and never reach the same state, and the depth is bounded by the number of regions.

start1·L1·T2·S2·I3·L

frontier top = next pop()

1 / 6

The frontier starts with a single node: the empty board.

Figure 1: Depth-first search on a tiny tree, with its frontier stack. 1·T means: put a T in region 1.
search.py
def depth_first_tree_search(problem):
    """
    [Figure 3.7]
    Search the deepest nodes in the search tree first.
    Search through the successors of a problem to find a goal.
    The argument frontier should be an empty queue.
    Repeats infinitely in case of loops.
    """

    frontier = [Node(problem.initial)]  # Stack

    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        frontier.extend(node.expand(problem))
    return None

Keeping everything connected

The rule “all shaded cells are connected” involves every region at once, so no single region can check it. The code encodes it in the graph: when a piece is placed, result rewrites that region’s edges so it is adjacent only to the regions its cells actually touch, and removes the reverse edges from the others. The graph then stays connected exactly as long as every placed piece can still be linked to the rest, with unfilled regions counted optimistically. actions returns no children if the graph has split, and goal_test accepts a state only when every region is filled and the graph is connected.Sidenote:Look at the graph in the Search state panel on the solver page: grey edges disappear the moment a piece is placed that does not touch that neighbour.

nuruomino.py
def _adjacency_graph_connected(self, adjacency_graph):
    """Return True if the adjacency graph is connected. False otherwise."""
    visited = set()
    queue = [1]
    while queue:
        region = queue.pop(0)
        if region in visited:
            continue
        visited.add(region)
        for neighbour in adjacency_graph[region]:
            if neighbour not in visited:
                queue.append(neighbour)
    return len(visited) == len(adjacency_graph)
nuruomino.py
def goal_test(self, state):
    """Test if the given state is a goal state."""
    return len(self.regions) == len(state.filled_regions) and
        self._adjacency_graph_connected(state.adjacency_graph)

See it run

To better understand how the solver works, you can explore any of these puzzles in the interactive demo in this page. Step through the Python code line by line, just like in a debugger, while inspecting the variables, call stack, search state, and how the board evolves as pieces are placed, tested, and removed during backtracking.

Go to About
Go to Projects
Go to Writing
Go to Resume
Toggle theme
Copy email
Open GitHub
Open LinkedIn
Subscribe (Atom feed)

↑↓ navigate · ↵ open · Ctrl↵ new tab · esc close