| 1 | 1 | def can_chain(dominoes): |
| 2 | | pass |
| 2 | # Edge Case: Empty set of dominoes |
| 3 | if not dominoes: |
| 4 | return [] |
| 5 | |
| 6 | # Edge Case: Single domino - check if both sides are equal |
| 7 | if len(dominoes) == 1: |
| 8 | if dominoes[0][0] == dominoes[0][1]: |
| 9 | return dominoes |
| 10 | else: |
| 11 | return None |
| 12 | |
| 13 | # Try all possible starting dominoes and orientations |
| 14 | for i in range(len(dominoes)): |
| 15 | # Try the domino in original orientation |
| 16 | chain = [dominoes[i]] |
| 17 | remaining = dominoes[:i] + dominoes[i+1:] |
| 18 | result = _build_chain(chain, remaining) |
| 19 | if result: |
| 20 | return result |
| 21 | |
| 22 | # Try the domino flipped |
| 23 | chain = [(dominoes[i][1], dominoes[i][0])] |
| 24 | remaining = dominoes[:i] + dominoes[i+1:] |
| 25 | result = _build_chain(chain, remaining) |
| 26 | if result: |
| 27 | return result |
| 28 | |
| 29 | # Edge Case: No valid chain exists |
| 30 | return None |
| 31 | |
| 32 | def _build_chain(chain, remaining): |
| 33 | # Base case: if no dominoes left, check if first and last match |
| 34 | if not remaining: |
| 35 | if chain[0][0] == chain[-1][1]: |
| 36 | return chain |
| 37 | else: |
| 38 | return None |
| 39 | |
| 40 | # Get the value we need to match (the second value of the last domino in chain) |
| 41 | target = chain[-1][1] |
| 42 | |
| 43 | # Try each remaining domino |
| 44 | for i in range(len(remaining)): |
| 45 | domino = remaining[i] |
| 46 | |
| 47 | # Try matching as-is |
| 48 | if domino[0] == target: |
| 49 | new_chain = chain + [domino] |
| 50 | new_remaining = remaining[:i] + remaining[i+1:] |
| 51 | result = _build_chain(new_chain, new_remaining) |
| 52 | if result: |
| 53 | return result |
| 54 | |
| 55 | # Try matching flipped |
| 56 | if domino[1] == target: |
| 57 | new_chain = chain + [(domino[1], domino[0])] |
| 58 | new_remaining = remaining[:i] + remaining[i+1:] |
| 59 | result = _build_chain(new_chain, new_remaining) |
| 60 | if result: |
| 61 | return result |
| 62 | |
| 63 | # Edge Case: No valid continuation found |
| 64 | return None |
| 65 | |
| 66 | # Handled Edge Cases: empty set of dominoes, single domino, no valid chain exists, disconnected components |