learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Knight's Tour Solver

Every square once, by always taking the hardest one first

Moves the knight each time to the square with the fewest onward moves and visits every square once: a fast greedy rule for Hamiltonian paths

Time: O(n · d²)
Space: O(n)
Use Case: Chess puzzles, Hamiltonian path heuristics, teaching greedy algorithms
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Knight's Tour (Warnsdorff's Rule)

A knight's tour is a sequence of knight moves that visits every square of a chessboard exactly once. On the knight's graph (one vertex per square, an edge for each knight move) it is a Hamiltonian path, and if the last square is a knight's move from the first it is a closed tour, a Hamiltonian cycle. The puzzle is centuries old: Euler studied it in 1759. Finding a Hamiltonian path is NP-hard in general, but on chessboards a simple greedy rule almost always succeeds.

How it works

Warnsdorff's rule (1823): from the current square, move to the unvisited square that has the fewest unvisited squares onward. Squares near the corners and edges have few exits, and visiting them early keeps them from becoming dead ends that would strand the knight later. Each move looks at the candidates and their onward counts, so a tour of n squares takes O(n · d²) with d at most 8. Ties matter: this visualizer breaks them in favour of the square farthest from the centre (Roth's rule), which completes every possible start on 5×5, 6×6 and 8×8 boards. Plain first-in-order ties fail from some squares. On 7×7, and on other graphs, the rule can still get stuck, and the visualizer says so.

Applications

The knight's tour is a classic exercise for backtracking and greedy heuristics in programming courses and interviews, and a gentle introduction to Hamiltonian paths and NP-hard problems. The same "most constrained first" idea runs through constraint solving (the minimum remaining values heuristic in sudoku and scheduling solvers) and graph colouring (DSatur). Knight's tours have also been used in puzzles, magic squares, art and simple encryption schemes.

Pseudocode

A greedy loop: from the last square, always go where the fewest onward moves remain.

WarnsdorffTour(G, start):
    tour = [start], mark start visited
    while |tour| < n:
        C = unvisited neighbours of the last square
        if C is empty: return tour     // stuck
        for each c in C:
            onward[c] = number of unvisited neighbours of c
        next = c in C with the smallest onward[c]
               (ties: farthest from the centre)
        append next to tour, mark it visited
    return tour

The onward count of a candidate does not count the current square, which is already visited. The rule never backtracks, so it either finishes in n − 1 moves or stops stuck.

Worked example, step by step

The tour from a1 on the 6 × 6 board loaded on this page.

Example graph: One vertex per square, a1 to f6, and an edge for each knight move: 36 vertices, 80 edges. Corners have 2 moves, central squares 8.

  1. From the corner. a1 has two moves, b3 and c2, both with 5 onward moves. Roth's tie rule picks b3, farther from the centre.
  2. Edges first. From b3 the knight goes to a5, which has only 2 onward moves left, then to c6 on the top edge.
  3. Around the edge. The tour keeps to the two outer rings, e5, f3, e1, c2, a3, b1, using up the squares with few exits before they are cut off.
  4. The centre late. The four central squares have 8 moves each and stay available as connectors: d4 is the 17th square, d3, c4 and c3 come among the last eleven.
  5. Finish. From c3 the last three squares follow, e4, f6 and d5. All 36 squares are visited.

A complete open tour ending on d5: d5 is not a knight's move from a1, so the tour is a Hamiltonian path, not a cycle.

Complexity, and where it comes from

Time: O(n · d²) · Space: O(n)

There are n − 1 moves. Each looks at the at most d candidates and counts the onward moves of each, at most d again, so O(d²) per move and O(n · d²) in all. With d ≤ 8 on a chessboard the tour is linear in the number of squares. A full backtracking search, by contrast, can take exponential time.

When to use Knight's Tour (Warnsdorff's Rule), and when not to

Knight's tours can be found in several ways, from greedy to exhaustive.

AlternativePrefer it whenCost
Plain backtrackingSmall boards, or to prove that no tour exists. Very slow on 8 × 8 without a good move order.Exponential
Warnsdorff + backtrackingUse the rule to order the moves and backtrack when stuck: finds tours on nearly every board almost instantly.Usually linear
Divide and conquer (Parberry)Very large boards: glue small precomputed tours together. Guaranteed closed tours on many sizes.O(n)

Common pitfalls

  • Ignoring ties. Many squares share the lowest onward count, and the tie-break decides whether the tour succeeds. "First in order" fails from some 5 × 5 squares where Roth's rule succeeds.
  • Expecting it to always work. It is a heuristic. On 7 × 7, even with Roth's rule, it completes the tour from only 15 of the 25 possible starting squares, and on irregular graphs it can get stuck early.
  • Starting from an impossible square. On an odd board, an open tour must start and end on squares of the corners' colour, since that colour has one square more. From the other colour no tour exists.

Frequently asked questions

What is a knight's tour?
A sequence of knight moves visiting every square of a board exactly once. If the last square is a knight's move from the first, the tour is closed.
Does a knight's tour exist on every board?
Open tours exist on n × n boards for n ≥ 5. Closed tours need an even number of squares, and Schwenk (1991) characterised the rectangular boards that have one.
Why does Warnsdorff's rule work so well?
Squares with few exits are the ones that can become dead ends. Visiting them early keeps the remaining squares well connected for as long as possible.
How many knight's tours are there on a chessboard?
There are 26,534,728,821,064 closed directed tours on the 8 × 8 board, found by computer, and far more open tours.

Related algorithms: Hamiltonian Path, Traveling Salesman Problem, Eulerian Path (Undirected), Depth-First Search, DSatur Coloring

An example graph: you can change it, or start blank.

Zoom Controls

37%
Nodes: 36
Edges: 80