VOOZH about

URL: https://www.geeksforgeeks.org/dsa/warndorffs-algorithm-in-python/

⇱ Warnsdorff's Algorithm in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Warnsdorff's Algorithm in Python

Last Updated : 30 May, 2026

Warnsdorff's algorithm is a heuristic method used to solve the Knight's Tour problem, a classic challenge in the field of combinatorial algorithms and chessboard puzzles. The Knight's Tour problem asks whether a knight can visit every square on a chessboard exactly once. This algorithm provides an efficient way to find such a tour, uses a simple but effective rule: always move the knight to the square that has the fewest onward moves.

In this article, we will explore Warnsdorff's algorithm and its implementation in Python, guiding you through the principles behind the heuristic and providing a step-by-step explanation of the code.

What is Warnsdorff's Algorithm?

The core idea behind Warnsdorff's algorithm is to reduce the chances of getting stuck in a corner or isolated area of the chessboard by always choosing the move that leads to the square with the fewest possible onward moves. This heuristic increases the likelihood of completing the tour.

Warnsdorff's Algorithm: A Step-by-Step Guide

Here’s a step-by-step breakdown of Warnsdorff's algorithm:

  1. Initialization: Place the knight on any starting position on the board.
  2. Move Selection: From the current position, evaluate all possible knight moves and count the number of valid onward moves from each potential position.
  3. Heuristic Choice: Choose the move that leads to the square with the fewest onward moves (Warndorff’s heuristic).
  4. Iteration: Repeat the move selection until the knight has visited all squares.

Implementing Warnsdorff's Algorithm in Python:

Below is the Python implementation of Warnsdorff's algorithm.


Output
Knight's Tour completed successfully:
[[ 0 33 2 17 48 31 12 15]
 [ 3 18 55 32 13 16 49 30]
 [56 1 34 47 54 51 14 11]
 [19 4 59 52 35 46 29 50]
 [40 57 36 45 60 53 10 25]
 [ 5 20 41 58 37 26 63 28]
...

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

Comment
Article Tags:
Article Tags: