progress

~/problems / Backtracking

Seating plan without feuding neighbours

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

You're seating guests along one side of a long table. Two feuding guests must never sit next to each other.

Write seatings(guests: list[str], feuds: list[tuple[str, str]]) -> list[list[str]]: every left-to-right order of all the guests with no feuding neighbours, in any order.

seatings(["ann", "bo", "cy"], [("ann", "bo")])
# [["ann", "cy", "bo"], ["bo", "cy", "ann"]]    cy has to sit in the middle

seatings(["ann", "bo"], [("bo", "ann")])        # []   feuds work both ways
seatings([], [])                                # [[]] one way to seat nobody
  • Up to 8 guests with distinct names; a feud may be listed twice.
  • Write the recursion yourself; don't use itertools.
Show hint

store feuds as a set of frozensets so "do these two feud?" is O(1). backtrack(row) tries each unused guest, skips them if they feud with row[-1], and otherwise appends, recurses and pops. Skipping early prunes every order that would start that way.

Topic: Recursion and backtracking. Choose, recurse, un-choose: subsets, permutations, N-queens, pruning.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc