VOOZH about

URL: https://www.geeksforgeeks.org/dsa/warnsdorffs-algorithm-knights-tour-problem/

⇱ Warnsdorff's algorithm for Knight’s tour problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Warnsdorff's algorithm for Knight’s tour problem

Last Updated : 23 Jul, 2025

Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once. 

Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight. 

👁 knight-tour-problem


We have discussed Backtracking Algorithm for solution of Knight's tour. In this post Warnsdorff's heuristic is discussed. 
Warnsdorff’s Rule:

  1. We can start from any initial position of the knight on the board.
  2. We always move to an adjacent, unvisited square with minimal degree (minimum number of unvisited adjacent).

This algorithm may also more generally be applied to any graph. 

Some definitions:

  • A position Q is accessible from a position P if P can move to Q by a single Knight's move, and Q has not yet been visited.
  • The accessibility of a position P is the number of positions accessible from P.

Algorithm:

  1. Set P to be a random initial position on the board
  2. Mark the board at P with the move number "1"
  3. Do following for each move number from 2 to the number of squares on the board: 
    • let S be the set of positions accessible from P.
    • Set P to be the position in S with minimum accessibility
    • Mark the board at P with the current move number
  4. Return the marked board — each square will be marked with the move number on which it is visited.

Below is implementation of above algorithm.  

Output:

59 14 63 32 1 16 19 34 
62 31 60 15 56 33 2 17
13 58 55 64 49 18 35 20
30 61 42 57 54 51 40 3
43 12 53 50 41 48 21 36
26 29 44 47 52 39 4 7
11 46 27 24 9 6 37 22
28 25 10 45 38 23 8 5

Time complexity: O(N^2)
Space complexity: O(N^2)

The Hamiltonian path problem is NP-hard in general. In practice, Warnsdorff's heuristic successfully finds a solution in linear time.

Do you know?
"On an 8 × 8 board, there are exactly 26,534,728,821,064 directed closed tours (i.e. two tours along the same path that travel in opposite directions are counted separately, as are rotations and reflections). The number of undirected closed tours is half this number, since every tour can be traced in reverse!"

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Comment
Article Tags: