1799. Full Board Knight Rides

Medium3.5 points estimatedBacktrackingMatrixDepth-First Search

A chess club has a small board with rows rows and cols columns. A knight starts on the square in row r and column c (both 0-based) and moves only with the usual L-shaped knight jump, never landing on a square it has already visited. A full ride is a sequence of moves that visits every square of the board exactly once; it may finish on any square.

Return the number of different full rides from the starting square. Two rides are different when their sequences of squares differ. On a 1 by 1 board the knight has already visited everything, so the answer is 1. Use depth-first backtracking with a visited mask, and prune whenever some unvisited square has no unvisited neighbour and is not a jump away from the knight, since nothing can ever reach it. The board holds at most 20 squares, so the search is exponential in rows * cols, with O(rows * cols) space.

Example 1

Input:
rows = 1cols = 1r = 0c = 0
Output:
1
Explanation:

The knight already stands on the only square, so there is exactly 1 ride.

Example 2

Input:
rows = 2cols = 2r = 0c = 0
Output:
0
Explanation:

A knight has no legal jump on a 2 by 2 board, so it cannot reach the other squares and the count is 0.

Example 3

Input:
rows = 3cols = 4r = 0c = 0
Output:
2
Explanation:

Starting in the corner of a 3 by 4 board, 2 different sequences visit all 12 squares.

Constraints

1 ≤ rows, cols; rows * cols ≤ 20

0 ≤ r < rows; 0 ≤ c < cols

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
Exponential in rows * cols with pruning
Space
O(rows * cols)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…