Skip to main content
Back to problems
#2596
Medium Algorithms

Check knight tour configuration

Array Depth-First Search Breadth-First Search Matrix Simulation
60.6% acceptance
Feb 25, 2026
525
65
There is a knight on an n x n chessboard. In a valid configuration, the knight starts at the top-left cell of the board and visits every cell on the board exactly once. You are given an n x n integer matrix grid consisting of distinct integers from the range [0, n * n - 1] where grid[row][col] indicates that the cell (row, col) is the grid[row][col]th cell that the knight visited. The moves are 0-indexed. Return true if grid represents a valid configuration of the knight's movements or false otherwise. Note that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn check_valid_grid(grid: Vec<Vec<i32>>) -> bool {
    // The knight must start at (0,0) with move 0.
    // For each consecutive pair of moves, the position change must be a valid knight move:
    // (|dr|, |dc|) must be (1,2) or (2,1).
    let n = grid.len();
    let total = n * n;
    // Build position map: pos[move] = (row, col)
    let mut pos = vec![(0usize, 0usize); total];
    for r in 0..n {
      for c in 0..n {
        pos[grid[r][c] as usize] = (r, c);
      }
    }
    if pos[0] != (0, 0) { return false; }
    for i in 1..total {
      let (r0, c0) = pos[i - 1];
      let (r1, c1) = pos[i];
      let dr = (r1 as i32 - r0 as i32).abs();
      let dc = (c1 as i32 - c0 as i32).abs();
      if !((dr == 1 && dc == 2) || (dr == 2 && dc == 1)) {
        return false;
      }
    }
    true
  }
}