Problem Description
Given the dimensions m x n of a board and a starting position (r, c) for a knight, find a sequence of moves by which the knight visits every cell on the board exactly once (the starting cell is counted as visited and must not be revisited). The board must be returned with each cell’s value indicating the order in which it was visited (starting from 0).
Key Insights
- This is a typical knight’s tour problem, solved using a backtracking/DFS approach.
- The knight’s valid moves are defined such that the smaller absolute difference in coordinates is 1 and the larger is 2.
- The board is small (m, n are at most 5), so an exhaustive backtracking solution is feasible.
- Mark each visited cell with the step count and backtrack if no valid moves are available.
- When all cells are filled, the path represents a valid knight tour.
Space and Time Complexity
Time Complexity: O(8^(mn)) in the worst case (exponential backtracking search, acceptable due to small board size). Space Complexity: O(mn) for the recursion stack and board storage.
Solution
We solve this problem using a DFS backtracking algorithm. We initiate an m x n board filled with a marker (e.g., -1) to indicate unvisited cells and mark the starting cell with 0. At each step, we try all possible knight moves. A move is valid if it lands within board boundaries and the cell is still unvisited.
We recursively explore each valid move, marking the cell with the current move number. If we eventually fill all cells (i.e., the move number reaches m * n), we have found a valid tour. If a move leads to a dead-end, we backtrack by resetting the cell’s value and trying a different move.
Key data structures and techniques:
- A 2D array (list or vector) for the board.
- A list (or array) that stores the eight possible moves of the knight.
- Recursive DFS with backtracking to explore potential move sequences.
- Boundary-checking and visited-checking logic to prune invalid moves.