Question

In Java: The n-queens puzzle is the problem of placing n queens on an n×n chessboard...

In Java:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. No two queens may be on the same row, column, nor diagonal.

The following image shows one possible solution for the 8-queens problem.

https://imgur.com/spcGSfj

The following are minimum requirements:

  • Get n from user (e.g. 4, 8, etc.). Input must be greater than 3 (there is no solution for n < 4).
  • Use arrays.
  • Use loops or recursion.
  • Print the solution. The following is the same solution to the 8-queens problem shown above, but in text
#################
# # # #X# # # # #
# # # # # # #X# #
# # #X# # # # # #
# # # # # # # #X#
# #X# # # # # # #
# # # # #X# # # #
#X# # # # # # # #
# # # # # #X# # #
#################
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Scanner;
public class Queens {

public static boolean safe(int[] mat, int n) {
for (int i = 0; i < n; i++) {
if (mat[i] == mat[n])
return false;
if ((mat[i] - mat[n]) == (n - i))
return false;   
if ((mat[n] - mat[i]) == (n - i))
return false;
}
return true;
}

//this function prints the queens
public static void print(int[] mat) {
int n = mat.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (mat[i] == j)
System.out.print("X ");
  
else
System.out.print("# ");
}
System.out.println();
}
System.out.println();
}


//this function does the backtracking and all the possible permutations are tried
public static void solution(int n) {
int[] arr = new int[n];
solution(arr, 0);
}

public static void solution(int[] mat, int k) {
int n = mat.length;
if (k == n)
print(mat);
else {
for (int i = 0; i < n; i++) {
mat[k] = i;
if (safe(mat, k))
solution(mat, k+1);
}
}
}


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of N(must be greater than 3): ");

int n = sc.nextInt();
solution(n);
}
}

Add a comment
Know the answer?
Add Answer to:
In Java: The n-queens puzzle is the problem of placing n queens on an n×n chessboard...
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
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