THINK FIRST·CODE LATER

← All labs

The knight's tour by backtracking

Problem

A chess knight must visit every square of an n × n board exactly once. Write KnightTour: read n and the starting row col (numbered from 0), and search for a tour by backtracking:

tour(r, c, move):
    if move > n × n: success
    for each free square (nr, nc) a knight's move away:
        number it 'move'                       ← choose
        if tour(nr, nc, move + 1): success     ← explore
        clear it                               ← un-choose
    failure

Try the candidate squares in the order of fewest onward moves first (Warnsdorff's rule) — with ties broken by the order of the eight moves (−2,+1), (−1,+2), (+1,+2), (+2,+1), (+2,−1), (+1,−2), (−1,−2), (−2,−1). Print the board with each square's move number in a field of width 3, or a message when no tour exists, then the number of recursive calls.

For the input

5 0 0

the program prints

  1 14  9 20  3
 24 19  2 15 10
 13  8 25  4 21
 18 23  6 11 16
  7 12 17 22  5
Recursive calls: 25

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d1-7-data-1.txt

5 0 0
What your program must print for d1-7-data-1.txt
  1 14  9 20  3
 24 19  2 15 10
 13  8 25  4 21
 18 23  6 11 16
  7 12 17 22  5
Recursive calls: 25

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d1-7-data-1.txt

Windows PowerShell does not understand <:

Get-Content d1-7-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.