LITS (ヌルオミノ) Solver
Nikoli's tetromino puzzle as a constraint satisfaction problem.
Table of contents
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
- No identical shapes touching
Two pieces of the same shape may not share an edge. Different shapes may.
brokenvalid - Everything is connected
All shaded cells form one group, joined by edges (corners do not count).
brokenvalid - No 2×2 blocks
Four shaded cells may never form a square.
brokenvalid
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.
Rules check
- waiting for Python…
Board
Solver
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 . Number the regions . A placement 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 and has a shape . Two sets of cells are adjacent, , when a cell of shares an edge with a cell of .
Variables, one per region:
Domains, the placements that fit inside each region:
Constraints, one per rule:
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_.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_ slides every orientation over every position of the grid and keeps it for a region when Action. agrees: all four cells lie inside that region (tetromino_) and the piece shares at least one edge with another region (num_). A piece touching no other region could never connect to the rest, so it is dropped before the search even starts.
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_actionsdef 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) > 0What 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_ is the set of regions that already have a piece. adjacency_ maps each region to the set of regions it touches. actions_ 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_ 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_), must not touch a piece of the same shape (_touches_, rule 1), must still be able to connect when all its neighbours are already filled (_connected_, rule 2), and must not complete a 2×2 block (_creates_, rule 3). The first failed test rejects it.
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 Truedef _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 Falsedef _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 Falsedef _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 FalsePlacing 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_. 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.
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_stateWhich 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.
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), [])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 search
depth_ 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.
frontier top = next pop()
- start next
The frontier starts with a single node: the empty board.
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 NoneKeeping 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_ 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.
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)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.