Write a Java program that attempts to solve the Knight\'s Tour for a given board
ID: 662236 • Letter: W
Question
Write a Java program that attempts to solve the Knight's Tour for a given board by random wandering. The Knight's Tour is an attempt to move the knight on a board, such that each space is visited exactly once. See the Web for more information.
The program should read 3 arguments: rows, columns, attempts . The first 2 arguments are the size of the board, rows x columns. The last argument is the number of attempts to make.
The knight will start at the upper-left corner, (1, 1). Look around, see what moves are available, and randomly choose one (note, that is not the same as randomly choosing a move, and then seeing if it's legal). If you have no more moves (and you haven't covered the board), then the knight didn't make it.
You then make another attempt, starting at (1, 1), until the knight succeeds, or you've used up the number of attempts. At the end, whichever the outcome, you will print a history of the knight's last attempt. E.g., given a 3x3 board, output:
Explanation / Answer
import java.awt.Point; import java.util.Scanner; /** * The Knight's Tour using backtracking * * @author Tyler Weaver */ public class TheKnigthsTour { private final static int BOARD_LENGTH = 8; //The length of the board private static int board[][]; //The simulated board //List of possible moves for the knight private static final Point[] MOVES = new Point[]{new Point(-2, -1), new Point(-2, 1), new Point(2, -1), new Point(2, 1), new Point(-1, -2), new Point(-1, 2), new Point(1, -2), new Point(1, 2)}; public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Enter starting row (0-7): "); int row = in.nextInt(); System.out.printf("Enter starting column (0-7): "); int col = in.nextInt(); solveTour(row, col); }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.