need help with this java lab: please read below and follow the steps! Copy and paste the code at
the bottom into your ide and go from there, please do not write a whole new program!
The purpose of this lab is to give you an opportunity to make use of a stack in the
implementation of a backtracking algorithm.
This problem is generally referred to as the N Queens problem. The gist of the problem is to
create an algorithm which can position N queens on a chess board so none of the queens can
attack any other queen. For those of you who may not be familiar with chess, the queen can
move horizontally, vertically, and diagonally. In the generalized N Queens problem, N represents
the number of rows and columns of the game board and the number of queens that must be
placed on the board in safe positions.
we will NOT be using recursion in any way to solve this problem.
The basic strategy that we will employ to solve this problem is to use backtracking. In this
particular case, what backtracking means is that we will make a move that is safe for a queen at
the time we make the move, but later on, we may discover that we are stuck and there is no safe
move available for the next queen we are trying to place on the board, so we must backtrack.
That means we will go back to the previous queen’s move, undo that move, and continue
searching for another safe place to put that queen. We will use the stack to remember where we
have placed queens on the board and when we need to back up, the queen at the top of the stack
will be popped and we will use that queen’s position to resume the search for the next safe
location.Stradegy below:
There are N rows. When a queen is placed into a row, that row cannot be used by other queens.
There are N columns. When a queen is placed into a column, that column cannot be used by
other queens.
There are 2 sets of diagonals to be concerned with, diagonals running upper left to lower right
and diagonals running upper right to lower left. There is a simple mathematical relationship
between N and the number of diagonals in each direction. When a queen is placed onto the
board, one left to right diagonal is no longer safe for other queens, and one right to left diagonal
is no longer safe for other queens.
Our approach to placing the queens on the board will be to use nested loops. As an example the
outer loop will be in control of which column we are currently searching for a spot to place a
queen. So, the first queen we place will be in column 0, and when the outer loop has completed
we will have placed N queens on the board, one in each column.
The inner loop will iterate through the rows, from 0 to N-1 until it finds a row R such that row R
is not taken by another queen, AND the 2 diagonals which intersect row R and the current
column are not taken by another queen. IF we find such a safe location, we push the current row,
column value onto a stack. Note: we can use the Java Point class to store the row and column
numbers in th.
need help with this java lab please read below and follow the steps.pdf
1. need help with this java lab: please read below and follow the steps! Copy and paste the code at
the bottom into your ide and go from there, please do not write a whole new program!
The purpose of this lab is to give you an opportunity to make use of a stack in the
implementation of a backtracking algorithm.
This problem is generally referred to as the N Queens problem. The gist of the problem is to
create an algorithm which can position N queens on a chess board so none of the queens can
attack any other queen. For those of you who may not be familiar with chess, the queen can
move horizontally, vertically, and diagonally. In the generalized N Queens problem, N represents
the number of rows and columns of the game board and the number of queens that must be
placed on the board in safe positions.
we will NOT be using recursion in any way to solve this problem.
The basic strategy that we will employ to solve this problem is to use backtracking. In this
particular case, what backtracking means is that we will make a move that is safe for a queen at
the time we make the move, but later on, we may discover that we are stuck and there is no safe
move available for the next queen we are trying to place on the board, so we must backtrack.
That means we will go back to the previous queen’s move, undo that move, and continue
searching for another safe place to put that queen. We will use the stack to remember where we
have placed queens on the board and when we need to back up, the queen at the top of the stack
will be popped and we will use that queen’s position to resume the search for the next safe
location.Stradegy below:
There are N rows. When a queen is placed into a row, that row cannot be used by other queens.
There are N columns. When a queen is placed into a column, that column cannot be used by
other queens.
There are 2 sets of diagonals to be concerned with, diagonals running upper left to lower right
and diagonals running upper right to lower left. There is a simple mathematical relationship
between N and the number of diagonals in each direction. When a queen is placed onto the
board, one left to right diagonal is no longer safe for other queens, and one right to left diagonal
is no longer safe for other queens.
Our approach to placing the queens on the board will be to use nested loops. As an example the
outer loop will be in control of which column we are currently searching for a spot to place a
queen. So, the first queen we place will be in column 0, and when the outer loop has completed
we will have placed N queens on the board, one in each column.
The inner loop will iterate through the rows, from 0 to N-1 until it finds a row R such that row R
is not taken by another queen, AND the 2 diagonals which intersect row R and the current
column are not taken by another queen. IF we find such a safe location, we push the current row,
2. column value onto a stack. Note: we can use the Java Point class to store the row and column
numbers in the x, y values of a Point object. By placing a queen’s location information into the
stack, we have affected the state of the board. We must update the state information to reflect
that a row is no longer safe for other queens. We also must update the state of the two diagonals
which intersect with the queen’s row, column position to indicate that those diagonals are no
longer available to other queens to be placed later. After updating the state information, we can
break out of the inner loop and continue on to the next column in the outer loop.
The backtracking aspect of this exercise occurs when the inner loop fails to find a spot to place a
queen in the current column. Inside the inner loop, we need to recognize that we have checked
position (row N-1, current column) and found that it is not safe. Therefore there is no safe place
for a queen in this column. Since we are stuck, we need to back up and try a different placement
for the previously placed queen. To backtrack, we need to undo the actions taken when we
placed the last queen onto the stack. That means pop the last queen off the stack, mark the row
and diagonals associated with that queen’s position as available again, and reset the row and
column loop control variables back to the point where they were when this queen was pushed
onto the stack (ie row = poppedPoint.x, column = poppedPoint.y). After backtracking the row
loop will continue to the next row to check if that row, column position is safe.
I am providing you with a partially completed Java FX project for this project. The project I am
giving you contains 2 classes. The GameBoard class provides methods for creation of the game
board based on the size given to its constructor. It also provides methods for placing and
removing a queen from a specific row, column position on the game board.
The JavaFxQueens class is the main application class. It determines what size the game board is
to be, creates an GameBoard object, and places the game board into a scene on the stage. It also
starts up a thread which will find safe places on the board for all the queens.
The placeQueens method in the JavaFxQueens class has not been completed. You must write the
code needed to find safe locations for all the queens. Whenever you find a safe place and push a
row, col position onto the stack, you must also call the placeQueen method on the GameBoard
object to draw that queen on the board. Whenever you backtrack and pop a row, col position off
the stack, you must also call the removeQueen method on the GameBoard object to remove that
queen from the game board display. Note, that after calling either one of these 2 methods, you
must call the delay method (which is provided) to slow down the rate at which moves are drawn
on the board so that every queen placed or removed is visible on the display for a reasonable
amount of time.
Think very carefully about how you want to organize the data which captures the state of the
game board (rows, diagonals). You do not need an actual representation of the game board (ie.
no 2 dimensional array). Also think carefully about how to mathematically capture the
3. relationship between a row, column position and which diagonals intersect that position. Part of
creating efficient programs is designing clever data representations which can be accessed in
very efficient ways from known information.
here is the code: please copy the java queens class and the gameboard class into your ide and
read the above to solve.
****javaQueens****
package javafxqueens;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
/**
*
* @author RVolkers
*/
public class JavaFxQueens extends Application implements Runnable {
private GameBoard board;
private int boardSize = 0;
@Override
public void start(Stage primaryStage) {
// Get the size of the game board from the user. Must be at least 5.
while(boardSize < 5)
{
boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board."));
}
board = new GameBoard(boardSize);
// The game board calculates how much display area it will need to display properly
Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize());
primaryStage.setTitle("N Queens");
primaryStage.setScene(scene);
primaryStage.show();
// Since the main thread is responsible for doing all the GUI updating,
// we need a separate thread to process the placement of queens. That thread
4. // will call methods on the GameBoard to tell the main thread where to place
// or remove queens on the board.
Thread thread = new Thread(this);
thread.start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
// Must do the main processing in a separate thread, so this class
// implements the Runnable interface.
@Override
public void run() {
// This thread calls a private method to figure out where the queens go
placeQueens();
}
// Used to slow down moves to enable seeing the board placement change
// as each queen is placed or removed from the board
private void delay()
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
}
// Figure out where to place the queens here....
// Call placeQueen and removeQueen methods on the gameBoard object when needed
private void placeQueens()
{
//insert new code here!
5. }
}
******gameboard******
package javafxqueens;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
/**
*
* @author RVolkers
*/
public class GameBoard extends GridPane {
private final int ButtonSize = 110;
private final int GapSize = 5;
private int size;
private Button[][] board;
public GameBoard() {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = 8;
createBoard();
}
public GameBoard(int n) {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = n;
6. createBoard();
}
private void createBoard() {
// Create an array to hold references to all the buttons on the board.
board = new Button[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
// Create each button with alternating colors
Button b = new Button();
b.setPrefSize(ButtonSize, ButtonSize);
if ((row + col) % 2 == 0) {
b.setStyle("-fx-background-color: red");
} else {
b.setStyle("-fx-background-color: black");
}
// Add the button to the board and to the GridPane
board[row][col] = b;
add(b, col, row);
}
}
}
// Calculate the size of the display based on the size
// of the buttons and the size of the gaps between buttons.
public double getDisplaySize() {
return size * ButtonSize + (size + 1) * GapSize;
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by adding the queen graphic to the appropriate button on the board
public void placeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(new ImageView("queen.gif"));
});
7. }
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by removing the queen graphic from the appropriate button on the board
public void removeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(null);
});
}
}
Solution
i add some methods for display the queens as Q and move the queens
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
public class JavaFxQueens extends Application implements Runnable {
private GameBoard board;
private int boardSize = 0;
@Override
public void start(Stage primaryStage) {
// Get the size of the game board from the user. Must be at least 5.
while(boardSize < 5)
{
boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board."));
}
board = new GameBoard(boardSize);
// The game board calculates how much display area it will need to display properly
8. Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize());
primaryStage.setTitle("N Queens");
primaryStage.setScene(scene);
primaryStage.show();
// Since the main thread is responsible for doing all the GUI updating,
// we need a separate thread to process the placement of queens. That thread
// will call methods on the GameBoard to tell the main thread where to place
// or remove queens on the board.
Thread thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
launch(args);
}
// Must do the main processing in a separate thread, so this class
// implements the Runnable interface.
@Override
public void run() {
// This thread calls a private method to figure out where the queens go
placeQueens();
}
// Used to slow down moves to enable seeing the board placement change
// as each queen is placed or removed from the board
private void delay()
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
}
// Figure out where to place the queens here....
// Call placeQueen and removeQueen methods on the gameBoard object when needed
9. //here we need on method for display the queens
public void showQueens(int[] s) {
int n = s.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (s[i] == j) {
System.out.print("Q");
} else {
System.out.print("");
}
}
System.out.println();
}
System.out.println();
}
public void placeQueens(int p, int n) {
for (int c = 0; c < n; c++) {
if (placeQueens(p, c)) {
s[r] = c;
if (r == n - 1) {
printQueens(s);
} else {
placeQueens(p + 1, n);
}
}
}
}
public void callplaceNqueens() {
placeQueens(0, s.length);
}
}
******gameboard******
package javafxqueens;
import javafx.application.Platform;
import javafx.geometry.Insets;
10. import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
/**
*
* @author RVolkers
*/
public class GameBoard extends GridPane {
private final int ButtonSize = 110;
private final int GapSize = 5;
private int size;
private Button[][] board;
public GameBoard() {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = 8;
createBoard();
}
public GameBoard(int n) {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = n;
createBoard();
}
private void createBoard() {
// Create an array to hold references to all the buttons on the board.
board = new Button[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
11. // Create each button with alternating colors
Button b = new Button();
b.setPrefSize(ButtonSize, ButtonSize);
if ((row + col) % 2 == 0) {
b.setStyle("-fx-background-color: red");
} else {
b.setStyle("-fx-background-color: black");
}
// Add the button to the board and to the GridPane
board[row][col] = b;
add(b, col, row);
}
}
}
// Calculate the size of the display based on the size
// of the buttons and the size of the gaps between buttons.
public double getDisplaySize() {
return size * ButtonSize + (size + 1) * GapSize;
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by adding the queen graphic to the appropriate button on the board
public void placeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(new ImageView("queen.gif"));
});
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by removing the queen graphic from the appropriate button on the board
public void removeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");