Is the Target's Cell Forced by Every Valid Seating?
Trees & GraphsAuto-graded · 25 test casesLast updated
Backtracking over placements of named items on a grid under pairwise relative-position clues, deciding whether the target ends up in one cell across all valid layouts.
Forced Cell on a Grid
You have a grid with rows rows and cols columns. Rows and columns are numbered from 1. Row 1 is the top row and column 1 is the leftmost column. A list of named items must be placed on the grid so that no two items share a cell. Each item occupies exactly one cell, and some cells may stay empty.
A list of clues restricts the placement. Every clue is a list of three strings [relation, a, b], where a and b are item names. The relation compares the position of a with the position of b:
| Relation | Condition |
|---|---|
same_row | row of a equals row of b |
same_column | column of a equals column of b |
left_of | column of a is strictly less than column of b (rows do not matter) |
right_of | column of a is strictly greater than column of b (rows do not matter) |
above | row of a is strictly less than row of b (columns do not matter) |
below | row of a is strictly greater than row of b (columns do not matter) |
A placement is valid if all items sit in distinct cells inside the grid and every clue holds.
Write a function that decides whether the cell of the item target is the same in every valid placement.
- If at least one valid placement exists and all valid placements put
targetin the same cell, return that cell as[row, column]. - Otherwise return
None.
Only the target's cell has to be forced. Other items may be free to move. For instance, if 50 valid placements exist and all of them put the target at row 2, column 3, the answer is [2, 3].
Return None in each of these situations:
- No valid placement exists, including contradictory clues.
- The target can occupy two or more different cells across valid placements.
- The input is malformed:
targetis not inentities, the entity names contain duplicates,rows < 1orcols < 1, there are more entities than cells, or some clue does not have exactly three elements, uses an unknown relation, or mentions an unknown name.
A clue that names the same item twice, such as ["same_row", "A", "A"], is evaluated normally. This one is always true. Strict relations such as ["left_of", "A", "A"] can never hold, so no valid placement exists.
Constraints
- Entity names are strings. Entities are small in number, so an exhaustive search with pruning is expected.
rowsandcolsare integers, with small values in practice.cluesmay be empty.- The result is a two-element list
[row, column](1-indexed) orNone.
Examples
Example 1
Input: forced_cell(2, 2, ['P', 'Q'], [['same_row', 'P', 'Q']], 'P')
Output: None
Example 2
Input: forced_cell(2, 2, ['P', 'Q'], [['left_of', 'P', 'Q']], 'P')
Output: None
Example 3
Input: forced_cell(1, 2, ['P', 'Q'], [], 'P')
Output: None
Hints
Hint 1
Treat this as a constraint-satisfaction problem: assign cells to items one at a time and undo the assignment when you backtrack.
Hint 2
A clue can be checked as soon as both of its items have been placed. If it fails, nothing placed later can fix it, so prune immediately.
Hint 3
You do not need to count every valid placement. Collect the distinct cells the target occupies, and stop as soon as you have seen two different ones.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a small constraint-satisfaction problem, and the clues are arbitrary pairwise relations, so we use backtracking with pruning.
- Validate the input. Return
Noneif the target is missing, names repeat, the grid is empty, there are more entities than cells, or any clue is malformed (wrong length, unknown relation, unknown name). - Parse the clues into
(relation, index_a, index_b)triples. - Choose an order. Entities that appear in more clues are placed first, so conflicts show up near the top of the search tree.
- Search. At each depth, try every unoccupied cell for the next entity. After the tentative placement, check every clue whose two entities are both placed. If one fails, undo the placement and try the next cell.
- Record the target's cell. When all entities are placed, add the target's cell to a set.
- Stop early. Once the set holds two different cells, the answer is
None, so every recursive level returns immediately.
At the end, if the set has exactly one cell, return it as [row, column]. Otherwise return None, which covers both "no valid placement" and "several possible target cells".
Why it is correct
- Pruning is safe. A clue between two placed entities depends only on their cells. If it fails, no later placement can repair it, so no valid full placement is lost.
- The search is complete. Every entity is tried in every free cell, and the
occupiedset enforces distinct cells. So every valid placement is reached unless we have already stopped early. - Early exit is safe. Two distinct target cells already force the answer
None. - Order does not change the result. The heuristic only changes the order in which placements are explored, not which ones exist.
Complexity
Let n be the number of entities, K = rows * cols, and m the number of clues.
- Time: at worst
O(K! / (K - n)! * m), which is exponential, as expected for a general constraint problem. Pruning and the early exit make typical inputs much faster. Indexing clues by entity would reduce the per-node check fromO(m)to the number of clues touching the entity just placed. - Space:
O(n + K + m)for the recursion, the position list, the occupied set, and the parsed clues. The target set never holds more than two cells.
Reference solution
from typing import List, Optional
def forced_cell(rows: int, cols: int, entities: List[str], clues: List[List[str]], target: str) -> Optional[List[int]]:
index = {name: i for i, name in enumerate(entities)}
if target not in index or len(index) != len(entities) or rows < 1 or cols < 1:
return None
if len(entities) > rows * cols:
return None
valid_relations = {"same_row", "same_column", "left_of", "right_of", "above", "below"}
parsed = []
for clue in clues:
if len(clue) != 3 or clue[0] not in valid_relations or clue[1] not in index or clue[2] not in index:
return None
parsed.append((clue[0], index[clue[1]], index[clue[2]]))
n = len(entities)
positions = [None] * n
occupied = set()
target_positions = set()
def satisfies(rel, a, b):
ar, ac = a
br, bc = b
if rel == "same_row":
return ar == br
if rel == "same_column":
return ac == bc
if rel == "left_of":
return ac < bc
if rel == "right_of":
return ac > bc
if rel == "above":
return ar < br
return ar > br
degree = [0] * n
for _, a, b in parsed:
degree[a] += 1
degree[b] += 1
order = sorted(range(n), key=lambda i: -degree[i])
def search(depth):
if len(target_positions) > 1:
return
if depth == n:
target_positions.add(positions[index[target]])
return
person = order[depth]
for r in range(1, rows + 1):
for c in range(1, cols + 1):
cell = (r, c)
if cell in occupied:
continue
positions[person] = cell
consistent = True
for rel, a, b in parsed:
if positions[a] is not None and positions[b] is not None and not satisfies(rel, positions[a], positions[b]):
consistent = False
break
if consistent:
occupied.add(cell)
search(depth + 1)
occupied.remove(cell)
positions[person] = None
if len(target_positions) > 1:
return
search(0)
if len(target_positions) == 1:
r, c = next(iter(target_positions))
return [r, c]
return None