Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2664: The Knight’s Tour

In this guide, we solve Leetcode #2664 The Knight’s Tour in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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).

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Array, Backtracking, Matrix

Intuition

We must explore combinations of choices, but many branches can be pruned early.

Backtracking enumerates valid candidates while keeping the search space under control.

Approach

Use DFS to build candidates step by step, and backtrack when constraints are violated.

Pruning keeps the exploration practical for typical constraints.

Steps:

  • Define the decision tree.
  • DFS through choices and backtrack.
  • Prune invalid paths early.

Example

Input: m = 1, n = 1, r = 0, c = 0 Output: [[0]] Explanation: There is only 1 cell and the knight is initially on it so there is only a 0 inside the 1x1 grid.

Python Solution

class Solution: def tourOfKnight(self, m: int, n: int, r: int, c: int) -> List[List[int]]: def dfs(i: int, j: int): nonlocal ok if g[i][j] == m * n - 1: ok = True return for a, b in pairwise((-2, -1, 2, 1, -2, 1, 2, -1, -2)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and g[x][y] == -1: g[x][y] = g[i][j] + 1 dfs(x, y) if ok: return g[x][y] = -1 g = [[-1] * n for _ in range(m)] g[r][c] = 0 ok = False dfs(r, c) return g

Complexity

The time complexity is O(8m×n)O(8^{m \times n})O(8m×n), and the space complexity is O(m×n)O(m \times n)O(m×n). The space complexity is O(m×n)O(m \times n)O(m×n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy