Approach
Depth-first search
For CCC 2019 S3 - Arithmetic Square, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 81 lines of Python from the credited upstream file ccc19s3.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3import sys, random4from copy import deepcopy5 6grid = [input().split() for i in range(3)]7for i in range(3):8 for j in range(3):9 if grid[i][j] != 'X':10 grid[i][j] = int(grid[i][j])11 12def deduce(a, b, c):13 if a != 'X' and b != 'X' and c != 'X':14 return (None, None, None)15 elif a != 'X' and b != 'X':16 return a, b, b + b-a17 elif a != 'X' and c != 'X':18 return a, (a+c)2, c19 elif b != 'X' and c != 'X':20 return b - (c-b), b, c21 else:22 return (None, None, None)23 24def full(grid):25 for r in grid:26 if 'X' in r:27 return False28 return True29 30def valid(grid):31 def ok(a, b, c):32 return c - b == b - a33 34 35 for i in range(3):36 if not ok(grid[i][0], grid[i][1], grid[i][2]):37 return False38 39 40 for j in range(3):41 if not ok(grid[0][j], grid[1][j], grid[2][j]):42 return False43 44 return True45 46def fill(grid):47 cont = True48 while cont:49 cont = False50 for i in range(3):51 a, b, c = deduce(grid[i][0], grid[i][1], grid[i][2])52 if a is not None:53 grid[i][0], grid[i][1], grid[i][2] = a, b, c54 cont = True55 56 a, b, c = deduce(grid[0][i], grid[1][i], grid[2][i])57 if a is not None:58 grid[0][i], grid[1][i], grid[2][i] = a, b, c59 cont = True60 61 return grid62 63 64def backtrack(grid):65 fill(grid)66 67 if full(grid) and valid(grid):68 for r in grid:69 print(*r)70 sys.exit()71 72 for i in range(3):73 for j in range(3):74 if grid[i][j] == 'X':75 newgrid = deepcopy(grid)76 newgrid[i][j] = 177 backtrack(newgrid)78 79 80while True:81 backtrack(grid)