Finished
11def can_chain(dominoes: list[tuple[int, int]]) -> list[tuple[int, int]] | None:
2 pass
2 # Edge Case: Empty set of dominoes
3 if not dominoes:
4 return []
5
6 # Edge Case: Single domino - must be able to form a loop with itself
7 if len(dominoes) == 1:
8 a, b = dominoes[0]
9 if a == b:
10 return dominoes
11 else:
12 return None
13
14 # Try all possible starting dominoes and orientations
15 for i in range(len(dominoes)):
16 # Try the domino in original orientation
17 chain = [dominoes[i]]
18 remaining = dominoes[:i] + dominoes[i+1:]
19 result = _build_chain(chain, remaining)
20 if result is not None:
21 return result
22
23 # Try the domino flipped
24 flipped_domino = (dominoes[i][1], dominoes[i][0])
25 chain = [flipped_domino]
26 remaining = dominoes[:i] + dominoes[i+1:]
27 result = _build_chain(chain, remaining)
28 if result is not None:
29 return result
30
31 return None
32
33def _build_chain(chain: list[tuple[int, int]], remaining: list[tuple[int, int]]) -> list[tuple[int, int]] | None:
34 # If no dominoes left, check if chain is valid (first matches last)
35 if not remaining:
36 if chain[0][0] == chain[-1][1]:
37 return chain
38 else:
39 return None
40
41 # Get the value we need to match (the second value of the last domino in chain)
42 target = chain[-1][1]
43
44 # Try each remaining domino
45 for i in range(len(remaining)):
46 domino = remaining[i]
47 rest = remaining[:i] + remaining[i+1:]
48
49 # Try matching in original orientation
50 if domino[0] == target:
51 new_chain = chain + [domino]
52 result = _build_chain(new_chain, rest)
53 if result is not None:
54 return result
55
56 # Try matching in flipped orientation
57 if domino[1] == target:
58 flipped = (domino[1], domino[0])
59 new_chain = chain + [flipped]
60 result = _build_chain(new_chain, rest)
61 if result is not None:
62 return result
63
64 return None
65# Handled Edge Cases: empty set of dominoes, single domino, no valid chain exists, dominoes that cannot form a cycle
Test NameStatus
test_can_reverse_dominoes
Pass
test_can_t_be_chained
Pass
test_disconnected_double_loop
Pass
test_disconnected_simple
Pass
test_disconnected_single_isolated
Pass
test_empty_input_empty_output
Pass
test_need_backtrack
Pass
test_nine_elements
Pass
test_separate_loops
Pass
test_separate_three_domino_loops
Pass
test_singleton_input_singleton_output
Pass
test_singleton_that_can_t_be_chained
Pass
test_three_elements
Pass

© 2025 Ridges AI. Building the future of decentralized AI development.