Question

JAVA code: (Knight’s tour)This chapter described the backtracking algorithm and how to use recursion to implement...

JAVA code:

(Knight’s tour)This chapter described the backtracking algorithm and how to use recursion to implement it.Another well-known chessboard problem that can be solved using the backtracking algorithm is a knight’s tour.Given an initial board position, determine a sequence of moves by a knight that will visit every square of the chessboard exactly once.For example,for a 5 × 5 and 6 × 6 square board,the sequence of moves are shown in Figure 5-22.


A knight moves by jumping two positions either vertically or horizontally and one position in the perpendicular direction.Write a recursive backtracking program that takes as input an initial board position and determines a sequence of moves by a knight that visits each square of the board exactly once.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java code:-


import java.util.*;
import java.io.*;

class Knight {
static int N = 8;


static boolean solutionKnightTour() {
int finalMat[][] = new int[8][8];

//Intializing matrix with -1
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
finalMat[x][y] = -1; //Solution matrix

/* aMove[] and bMove[] indicates next move of Knight.
aMove[] is for next value of x coordinate
bMove[] is for next value of y coordinate */
int aMove[] = {2, 1, -1, -2, -2, -1, 1, 2};
int bMove[] = {1, 2, 2, 1, -1, -2, -2, -1};

// Since the Knight is initially at the first block
finalMat[0][0] = 0;

/* Start from 0,0 and explore all tours using
solveKnightTourUtil() */
if (!solutionKnightTourUtil(0, 0, 1, finalMat, aMove, bMove)) {
System.out.println("Solution does not exist");
return false;
} else
printSolution(finalMat);

return true;
}

static boolean isMatSafeToUse(int a, int b, int finalMat[][]) {
return (a >= 0 && a < N && b >= 0 &&
b < N && finalMat[a][b] == -1);
}

//printing the final matrix
static void printSolution(int finalmat[][]) {
for (int a = 0; a < N; a++) {
for (int b = 0; b < N; b++)
System.out.print(finalmat[a][b] + " ");
System.out.println();
}
}

/* we use recursive utility function to solve Knight
Tour problem */
static boolean solutionKnightTourUtil(int a, int b, int movei,
int finalmat[][], int aMove[],
int bMove[]) {
int k, next_a, next_b;
if (movei == N * N)
return true;

/* Try all next moves from the current coordinate
x, y */
for (k = 0; k < 8; k++) {
next_a = a + aMove[k];
next_b = b + bMove[k];
if (isMatSafeToUse(next_a, next_b, finalmat)) {
finalmat[next_a][next_b] = movei;
if (solutionKnightTourUtil(next_a, next_b, movei + 1,
finalmat, aMove, bMove))
return true;
else
finalmat[next_a][next_b] = -1;// backtracking
}
}

return false;
}

/* main program to run above functions */
public static void main(String args[]) {
solutionKnightTour();
}
}

Add a comment
Know the answer?
Add Answer to:
JAVA code: (Knight’s tour)This chapter described the backtracking algorithm and how to use recursion to implement...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • in c++ Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the...

    in c++ Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide missing logic for the class Queens that will enable it to create a two-dimensional array that...

  • I need help with my programming assignment. The language used should be java and the algorithm...

    I need help with my programming assignment. The language used should be java and the algorithm should use search trees so that you play against the computer and he chooses the best move. The tree should have all possibilities on the leaves and you could use recursion to so that it populates itself. The game can be a 3*3 board (no need the make it n*n). Please put comments so that I can understand it. Thanks The game of ‘Walls’...

  • JAVA Sudoku.java This class does the work of solving the Sudoku puzzle, as well as containing...

    JAVA Sudoku.java This class does the work of solving the Sudoku puzzle, as well as containing the main method to provide a text-based user interface. Stores a Board object which it uses in solving. It should also track statistics about the solving process: the number of recursive calls made, and the number of "backups" that had to be done. public Sudoku( Scanner sc ) Constructor for the Sudoku class. Initializes the board and other instance variables. public boolean solve( Location...

  • Please help i need a C++ version of this code and keep getting java versions. Please...

    Please help i need a C++ version of this code and keep getting java versions. Please C++ only Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide...

  • Write a JAVA program to solve a sudoku! Given a partially filled 9×9 2D array ‘grid[9][9]’,...

    Write a JAVA program to solve a sudoku! Given a partially filled 9×9 2D array ‘grid[9][9]’, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9. I have posted 3 input files: sudoku1.txt, sudoku2.txt and sudoku3.txt Problem Analysis & Design - Think about how you will need to solve this problem. You should do an...

  • CMPS 12B Introduction to Data Structures Programming Assignment 2 In this project, you will write...

    can i get some help with this program CMPS 12B Introduction to Data Structures Programming Assignment 2 In this project, you will write a Java program that uses recursion to find all solutions to the n-Queens problem, for 1 Sns 15. (Students who took CMPS 12A from me worked on an iterative, non-recursive approach to this same problem. You can see it at https://classes.soe.ucsc.edu/cmps012a/Spring l8/pa5.pdf.) Begin by reading the Wikipcdia article on the Eight Queens puzzle at: http://en.wikipedia.org/wiki/Eight queens_puzzle In...

  • What is the role of polymorphism? Question options: Polymorphism allows a programmer to manipulate objects that...

    What is the role of polymorphism? Question options: Polymorphism allows a programmer to manipulate objects that share a set of tasks, even though the tasks are executed in different ways. Polymorphism allows a programmer to use a subclass object in place of a superclass object. Polymorphism allows a subclass to override a superclass method by providing a completely new implementation. Polymorphism allows a subclass to extend a superclass method by performing the superclass task plus some additional work. Assume that...

  • In this part, you will complete the code to solve a maze.

    - Complete the code to solve a maze- Discuss related data structures topicsProgramming-----------In this part, you will complete the code to solve a maze.Begin with the "solveMaze.py" starter file.This file contains comment instructions that tell you where to add your code.Each maze resides in a text file (with a .txt extension).The following symbols are used in the mazes:BARRIER = '-' # barrierFINISH = 'F' # finish (goal)OPEN = 'O' # open stepSTART = 'S' # start stepVISITED = '#' #...

  • The following guidelines outline the basic template for a robot vacuum cleaner game. The game must be implemented in c programming language. It mimics a robotic vacuum cleaner. The code must only use...

    The following guidelines outline the basic template for a robot vacuum cleaner game. The game must be implemented in c programming language. It mimics a robotic vacuum cleaner. The code must only use the following libraries: #include <math.h> #include <stdlib.h> #include <string.h> #include <limits.h> and any .graphics and .timers libraries. The guidelines are outlined as follows: Terminal Set-up: you may assume that the terminal will be quite large, for example, on the order of 150×50, or more. Status Display: The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT