Question

Please Note: I have been asked to modify the NQueens problem in whichever way I like. I have thought of this way and want to implement it. It is NOT a direct Homework question, rather it is a question of how do I implement my own modification.

I have written a code below that solves for 4 Queens. So according to this code, no two queens can be in the same row, same column and same diagonal so as to be non-attacking. I am trying to modify it such that if I place a queen then it can be placed in the same column but skipping two rows, it can be placed in the same row skipping two columns and similarly it can be placed in the same diagonal skipping two rows and two columns.

So basically, in simple words, the queen can be placed in the same row, same column and same diagonal skipping two blocks.

For 4 queens output currently looks like this:

* Q * *
* * * Q
Q * * *
* * Q *

and

* * Q *
Q * * *
* * * Q
* Q * *

But is should also give the following output:

Q * * Q
* * * *
* * * *
Q * * Q

So here the queen has been placed after every two blocks, horizontally, vertically and diagonally.

Code:

import java.util.*;

public class Queens {

/***************************************…
* Return true if queen placement q[n] does not conflict with
* other queens q[0] through q[n-1]
****************************************/
public static boolean isConsistent(int[] q, int n) {
for (int i = 0; i < n; i++) {
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}

/***************************************…
* Print out N-by-N placement of queens from permutation q in ASCII.
****************************************/
public static void printQueens(int[] q) {
int N = q.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
} 
System.out.println();
}


/***************************************…
* Try all permutations using backtracking
****************************************/
public static void enumerate(int N) {
int[] a = new int[N];
enumerate(a, 0);
}

public static void enumerate(int[] q, int n) {
int N = q.length;
if (n == N) printQueens(q);
else {
for (int i = 0; i < N; i++) {
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
}
} 


public static void main(String[] args) {

enumerate(4);
}

}

What am I doing wrong? How do I change my code so that it works with the modification?

Was it helpful?

Solution

It's impossible in your model.
In your model queens' have next coordinates:

Oy = q[Ox];  

in result

Q * * Q
* * * *
* * * *
Q * * Q 

array should have two values on same posistion

q[0] == 0  
q[0] == 3  
q[3] == 0  
q[3] == 3  

It's impossible in 1-dimensional array. You should change model and algorithm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top