Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Here is a code of N-Queens Problem. This solution works in the way that no two queens can't attack each other. I am attaching a

Here is a code of N-Queens Problem. This solution works in the way that no two queens can't attack each other. I am attaching a doc file for reference.

In the same way I was assigned to make a java code to place knights so that no two knights can't attack each other. The Chess board should be 8*8 chess board. Please provide a fruitful solution as i have posted the same question twice but cannot get an accurate answer. Please Refer the Code for understanding the solution and vice versa.

Here is the JAVA Code for non attacking Queens:

package queens;

public class Queens {

int[] x;

public Queens(int N) {

x = new int[N];

}

public boolean canPlaceQueen(int r, int c) {

/**

* Returns TRUE if a queen can be placed in row r and column c.

* Otherwise it returns FALSE. x[] is a global array whose first (r-1)

* values have been set.

*/

for (int i = 0; i < r; i++) {

if (x[i] == c || (i - r) == (x[i] - c) || (i - r) == (c - x[i])) {

return false;

}

}

return true;

}

public void printQueens(int[] x) {

int N = x.length;

for (int i = 0; i < N; i++) {

for (int j = 0; j < N; j++) {

if (x[i] == j) {

System.out.print("Q ");

} else {

System.out.print("* ");

}

}

System.out.println();

}

System.out.println();

}

public void placeNqueens(int r, int n) {

/**

* Using backtracking this method prints all possible placements of n

* queens on an n x n chessboard so that they are non-attacking.

*/

for (int c = 0; c < n; c++) {

if (canPlaceQueen(r, c)) {

x[r] = c;

if (r == n - 1) {

printQueens(x);

} else {

placeNqueens(r + 1, n);

}

}

}

}

public void callplaceNqueens() {

placeNqueens(0, x.length);

}

public static void main(String[] args) {

Queens Q = new Queens(8);

Q.callplaceNqueens();

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

The Structure Of The Relational Database Model

Authors: Jan Paredaens ,Paul De Bra ,Marc Gyssens ,Dirk Van Gucht

1st Edition

3642699588, 978-3642699580

More Books

Students also viewed these Databases questions

Question

2 What supply is and what affects it.

Answered: 1 week ago