The Knight's Tour - Problem
Given two positive integers m and n which represent the height and width of a 0-indexed 2D board, and a pair of positive integers (r, c) representing the starting position of a knight on the board.
Your task is to find an order of movements for the knight such that every cell of the board gets visited exactly once (the starting cell is considered visited and shouldn't be visited again).
Return the 2D array board where each cell's value shows the order of visiting that cell, starting from 0 (the initial position of the knight).
Note: A knight can move from cell (r1, c1) to cell (r2, c2) if:
0 <= r2 <= m - 1and0 <= c2 <= n - 1min(abs(r1 - r2), abs(c1 - c2)) = 1andmax(abs(r1 - r2), abs(c1 - c2)) = 2
Input & Output
Example 1 — Small 3×3 Board
$
Input:
m = 3, n = 3, r = 1, c = 0
›
Output:
[[0,7,2],[5,2,1],[6,3,8]]
💡 Note:
Knight starts at (1,0) with move 0, then follows L-shaped moves to visit all 9 cells exactly once, ending at (2,2) with move 8
Example 2 — Corner Start
$
Input:
m = 3, n = 4, r = 0, c = 0
›
Output:
[[0,3,8,5],[9,6,1,4],[2,11,10,7]]
💡 Note:
Knight starts at corner (0,0), visits all 12 cells in order, demonstrating tour from corner position
Example 3 — Minimum 2×2
$
Input:
m = 2, n = 2, r = 0, c = 0
›
Output:
[[-1,-1],[-1,-1]]
💡 Note:
No valid knight's tour exists on 2×2 board since knight needs L-shaped moves which require at least 3×3 space
Constraints
- 1 ≤ m, n ≤ 10
- 0 ≤ r < m
- 0 ≤ c < n
Visualization
Tap to expand
Understanding the Visualization
1
Input Board
3×3 board with knight starting at position (1,0)
2
Knight Moves
Knight makes L-shaped moves visiting each cell once
3
Complete Tour
Final board shows visit order from 0 to 8
Key Takeaway
🎯 Key Insight: Backtracking with Warnsdorff's heuristic efficiently finds valid knight tours by choosing moves with minimum onward options
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code