KenKen You Do It?
Time limit2sMemory limit256 MB
Count the assignments of numbers 1 to n to the given cage cells that meet the target under the operator with distinct values in shared rows and columns.
- Level
Medium5 of 10
- Topics
- Backtracking, Brute force
- Solved
- No attempts yet
Problem
KenKen is a logic puzzle that appeared in Japan in 2004. A puzzle is an grid cut into sections that do not overlap, and each section carries an integer target together with one arithmetic operator. You fill the whole grid with numbers from 1 to so that both rules hold:
- no number appears twice in the same row or in the same column
- in every section the numbers of that section reach the target of the section under the operator of the section
This problem looks at a single section, not at a whole puzzle. The figure shows two sections taken from an puzzle, each with some of the ways its squares can be filled.

The operator decides what the numbers of the section must satisfy:
+: the numbers add up to*: the numbers multiply to-: the section has exactly two squares, and the larger number minus the smaller one is/: the section has exactly two squares, and the larger number divided by the smaller one is with no remainder
Squares outside the section do not matter. Two squares of the section that lie in the same row, or in the same column, still have to hold different numbers. Two fillings are different when some square holds a different number.
Placed in a puzzle, the first section of the figure gains two more fillings, the ones that use 9 and 2. In the first filling of the second section you cannot swap the 1 and the 4 of the top row, because that puts two 1s in the same column.
Input
The first line contains , , and op. Here is the size of the puzzle that holds the section, is the number of squares in the section, is the target value, and op is one of +, -, *, /.
After that come grid positions, each written as a row number and a column number . The positions take up one or more lines.
The squares of a section are connected: from any square of the section you reach every other square of the section by crossing shared edges between squares.
The values satisfy , , and .
Output
Print the number of ways the section can be filled in a KenKen puzzle of the given size.