06. Knight's Tour Problem
β GFG solution to the Knight's Tour Problem: find a sequence where a knight visits every square on an nΓn chessboard exactly once using backtracking. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an integer n, representing an n Γ n chessboard with a Knight starting at the top-left corner (0, 0). Your task is to determine a valid Knight's Tour, where the Knight visits every square exactly once, following the standard movement rules of a chess Knight.
A Knight moves in an L-shape: two steps in one direction (horizontal or vertical) and one step perpendicular to that direction. For example, if a Knight is at cell (2, 2), it can move to any of these cells: (4, 3), (4, 1), (0, 3), (0, 1), (3, 4), (3, 0), (1, 4), and (1, 0).
Return the order in which each cell is visited (starting from 0). If a solution exists, return the sequence of numbers representing the order of visited squares. If no solution is possible, return an empty list.
π Examples
Example 1
Input: n = 5
Output: true
Explanation: A possible Knight's Tour in a 5x5 chessboard is:
[[0, 11, 2, 17, 20],
[3, 16, 19, 12, 7],
[10, 1, 6, 21, 18],
[15, 4, 23, 8, 13],
[24, 9, 14, 5, 22]]
Each number represents the step at which the Knight visits that cell, starting from (0, 0) as step 0.Example 2
π Constraints
$1 \le n \le 6$
β
My Approach
The optimal approach uses Backtracking with Depth-First Search (DFS) to explore all possible knight moves and find a valid tour:
Backtracking with DFS
Initialize Board:
Create an
n Γ nboard initialized with-1(unvisited cells).Mark the starting position
(0, 0)with0(first step).
Define Knight Moves:
A knight can move in 8 possible directions:
(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(1,-2),(2,-1).Store these as direction arrays
dx[]anddy[].
Recursive Exploration:
From current position
(x, y)at steps, try all 8 possible knight moves.For each valid move to
(nx, ny):Check if the new position is within bounds and unvisited.
Mark the cell with the current step number.
Recursively explore from the new position with step
s + 1.
Base Case:
If
s == n * n, all cells are visited - returntrue.
Backtrack:
If a path doesn't lead to a solution, reset the cell to
-1and try the next move.If no valid move exists from current position, backtrack to previous state.
Return Result:
If a complete tour is found, return the board with the visiting sequence.
Otherwise, return an empty list.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(8^(nΒ²)), where n is the size of the chessboard. In the worst case, we explore all possible knight move sequences. However, with pruning through backtracking, practical runtime is much better, especially for smaller boards (n β€ 6). The branching factor is 8 (possible knight moves) and maximum depth is nΒ².
Expected Auxiliary Space Complexity: O(nΒ²), where n is the size of the board. This includes space for the board storage and the recursion call stack which can go up to depth nΒ² in the worst case.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Warnsdorff's Heuristic Approach
π‘ Algorithm Steps:
Always move the knight to the square with minimum accessibility (fewest onward moves).
Count unvisited neighbors for each possible next position.
Choose the position with the least number of unvisited neighbors.
Significantly reduces backtracking by making smarter choices.
π Complexity Analysis:
Time: β±οΈ O(nΒ²) - Near-linear with heuristic guidance
Auxiliary Space: πΎ O(nΒ²) - Board storage and recursion stack
β
Why This Approach?
Dramatically faster than pure backtracking
Intelligently reduces search space
Industry-standard heuristic for knight's tour
π 3οΈβ£ Iterative DFS with Stack
π‘ Algorithm Steps:
Use an explicit stack to avoid recursion overhead.
Push starting position with step count onto stack.
Pop states and try all valid knight moves iteratively.
Backtrack by popping states when no valid moves exist.
π Complexity Analysis:
Time: β±οΈ O(8^(nΒ²)) - Explores all possible paths
Auxiliary Space: πΎ O(nΒ²) - Stack space proportional to board size
β
Why This Approach?
Avoids recursion stack overflow for very large boards
More control over backtracking process
Suitable for systems with limited stack size
π 4οΈβ£ Divide and Conquer Approach
π‘ Algorithm Steps:
Solve for smaller sub-boards and combine solutions.
Use precomputed patterns for standard board sizes.
Handle edge cases separately for odd-sized boards.
Merge partial tours to create complete solution.
π Complexity Analysis:
Time: β±οΈ O(8^(nΒ²)) - Similar to basic backtracking
Auxiliary Space: πΎ O(nΒ²) - Board and recursion stack
β
Why This Approach?
Can leverage precomputed patterns for efficiency
Better for specific board sizes with known solutions
Theoretical improvement for very large boards
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π Simple Backtracking
π΄ O(8^(nΒ²))
π’ O(nΒ²)
π Easy to understand
π Very slow for n>6
π Warnsdorff's Heuristic
π’ O(nΒ²)
π’ O(nΒ²)
π Very fast practically
β οΈ May fail on some boards
π Iterative DFS
π‘ O(8^(nΒ²))
π’ O(nΒ²)
π― No stack overflow
π§ More complex code
π Divide and Conquer
π‘ O(8^(nΒ²))
π’ O(nΒ²)
β Good for specific sizes
π§ Complex implementation
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Large boards (n β₯ 8)
π₯ Warnsdorff's Heuristic
β β β β β
π Small boards (n β€ 6)
π₯ Simple Backtracking
β β β ββ
π§ Deep recursion concerns
π₯ Iterative DFS
β β β β β
π― Interview/Competitive
π Basic Backtracking
β β β β β
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated