Problem
Given two positive integers m
and n
which are the height and width of a
0-indexed 2D-array board
, a pair of positive integers (r, c)
which is the starting position of the knight on the board.
Your task is to find an order of movements for the knight, in a manner that every cell of the board
gets visited exactly once (the starting cell is considered visited and you shouldn ’t visit it again).
Return the array board
in which the cells ’ values show the order of visiting the cell starting from 0 (the initial place of the knight).
Note that a knight can move from cell (r1, c1)
to cell (r2, c2)
if
0 <= r2 <= m - 1
and 0 <= c2 <= n - 1
and min(abs(r1 - r2), abs(c1 - c2)) = 1
and max(abs(r1 - r2), abs(c1 - c2)) = 2
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= m, n <= 5
0 <= r <= m - 1
0 <= c <= n - 1
- The inputs will be generated such that there exists at least one possible order of movements with the given condition
Solution
Method 1 - Backtracking
We use backtracking to try all possible knight moves, filling the board in the order of the knight’s tour. Since the board is small (max 5x5), this is efficient enough.
Code
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O((m*n)!)
in the worst case (but feasible for m,n ≤ 5). - 🧺 Space complexity:
O(m*n)
for the board and recursion stack.