#2596

Check Knight Tour Configuration

Medium
ArrayDepth-First SearchBreadth-First SearchMatrixSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

We can optimize the brute-force approach by directly validating the knight's moves using a set of pre-computed valid positions. This allows us to quickly check if each move is valid without iterating through all possible moves.

⚙️

Algorithm

2 steps
  1. 1Step 1: Create a mapping of each number to its position on the grid.
  2. 2Step 2: For each number from 0 to n*n - 1, check if the move to the next number is valid using the pre-computed positions.
solution.py10 lines
1def checkKnightTour(grid):
2    n = len(grid)
3    moves = [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]
4    position = {grid[r][c]: (r, c) for r in range(n) for c in range(n)}
5    for i in range(n * n - 1):
6        r1, c1 = position[i]
7        r2, c2 = position[i + 1]
8        if not any((r1 + dr == r2 and c1 + dc == c2) for dr, dc in moves):
9            return False
10    return True

Complexity note: We still iterate through the grid to build the position mapping, which takes O(n²). However, we use a dictionary to access positions in constant time, making the move validation efficient.

  • 1Understanding knight moves is crucial.
  • 2Mapping positions allows for faster validation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.