The Jane Street puzzle for June 2022. Implemented the solution with backtracking.
The original problem statement can be found here.
Fill each region with the numbers 1 through N, where N is the number of cells in the region. For each number K in the grid, the nearest K via taxicab distance must be exactly K cells away.
Once the grid is completed, the answer to the puzzle is found as follows: compute the product of the values in each row, and then take the sum of these products.
To give proper notation to the problem:
Given a
Iterate through every different configuration of the cells to fill the grid, return True if all of the followings hold:
- Every region
$R_i$ consists of unique values$1, 2, ...,|R_i|$ only. - For every cell, denote its value by
$K$ , the nearest$K$ is exactly$K$ units away.
Denote
For each cell
- (Local neighbor check) Check that the nearest
$K$ is at least$K$ units away. Raise failure if the boundary of$K$ -ball (centered at$c$ ) has been filled but does not contain any$K$ . - (Global neighbor check) For each cell
$s$ with value$S$ in the grid, if$s$ is exactly$S$ units away from the newly added cell$c$ , then perform local neighbor check on$s$ .
Denote
Step (1) takes
For step (2), note that a boundary of a
Combining the property of backtracking and time required for local and global neighbor checks gives
- Memorization helps optimize the performance. For this problem, it is found useful to store mappings like
- cell position
$\mapsto$ region - cell position, value
$K$ $\mapsto$ boundary of$K$ -ball
- cell position
- For this problem in particular, it is found faster to start backtracking with smaller regions.