1. Pure DFS Backtracking (Arbitrary Move Order)
Intuition
Place knight at (0, 0) with step 0. From (r, c), iterate through the 8 directions in fixed array order. If next cell is inside board and unvisited, mark with step + 1 and recurse. If all 8 moves fail, reset cell to -1 and return false.
When to apply: Sufficient for small boards (N <= 5).
Algorithm
- Initialize
N x Nboard with -1. - Set
board[0][0] = 0. - In
solve(r, c, step): - - If
step == N * N, return true (tour complete). - - Loop
kfrom 0 to 7 for 8 knight moves: - - If
(nr, nc)is valid andboard[nr][nc] == -1: - -
board[nr][nc] = step. - - If
solve(nr, nc, step + 1)returns true, return true. - - Backtrack:
board[nr][nc] = -1. - - Return false.
#include <iostream>#include <vector> using namespace std; class Solution { int dx[8] = {2, 1, -1, -2, -2, -1, 1, 2}; int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1}; bool solve(int r, int c, int step, int n, vector<vector<int>>& board) { if (step == n * n) return true; for (int i = 0; i < 8; i++) { int nr = r + dx[i]; int nc = c + dy[i]; if (nr >= 0 && nr < n && nc >= 0 && nc < n && board[nr][nc] == -1) { board[nr][nc] = step; if (solve(nr, nc, step + 1, n, board)) return true; board[nr][nc] = -1; // backtrack } } return false; } public: vector<vector<int>> knightsTour(int n) { vector<vector<int>> board(n, vector<int>(n, -1)); board[0][0] = 0; if (solve(0, 0, 1, n, board)) return board; return {}; }}; int main() { Solution sol; auto board = sol.knightsTour(5); for (const auto& row : board) { for (int v : row) printf("%2d ", v); cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(8^(N^2))— Worst-case branching factor of 8 at each of the N2 cells. - Space complexity:
O(N^2)— Recursion call stack depth is N2.