# Eight Queens Problem

• 01-28-2012, 11:24 PM
Jtrtoday
Eight Queens Problem
Hello, I've been trying to make a Eight Queens program solution program, and I came across this code, i was wondering if some one could explain it to me as I don't fully
understand what this code is doing..
Thanks!

public class NQueens {

private static int[] b = new int[8];
private static int s = 0;

static boolean unsafe(int y) {
int x = b[y];
for (int i = 1; i <= y; i++) {
int t = b[y - i];
if (t == x ||
t == x - i ||
t == x + i) {
return true;
}
}

return false;
}

public static void putboard() {
System.out.println("\n\nSolution " + (++s));
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
System.out.print((b[y] == x) ? "|Q" : "|_");
}
System.out.println("|");
}
}

public static void main(String[] args) {
int y = 0;
b[0] = -1;
while (y >= 0) {
do {
b[y]++;
} while ((b[y] < 8) && unsafe(y));
if (b[y] < 8) {
if (y < 7) {
b[++y] = -1;
} else {
putboard();
}
} else {
y--;
}
}
}
}
• 01-28-2012, 11:35 PM
diamonddragon
Re: Eight Queens Problem
Can You precise what is that You don't understand?
• 01-28-2012, 11:39 PM
Jtrtoday
Re: Eight Queens Problem
I get everything but the Main method of the program

why is the y-- at the end

if y > 8 then it subtracts 1 from y, but then would it just add 1 to y again and wouldn't you be stuck in the loop?
• 01-29-2012, 12:07 AM
diamonddragon
Re: Eight Queens Problem
What is this part of code doing?

Code:

```  if (y < 7) {     b[++y] = -1;     } ...```
• 01-29-2012, 12:27 AM
diamonddragon
Re: Eight Queens Problem
As I understood this part, it says:

Code:

```While board column >= 0     set Queen at column y   Untill it is safe and Queen at column y has position inside board of 8 fields   If Queen at position y is inside board of 8 fields(0-7)       ...   if not decrease y, because y is out of board.```

Code:

```while (y >= 0) {     do {            b[y]++;       }   while ((b[y] < 8) && unsafe(y));   if (b[y] < 8) {       if (y < 7) {           b[++y] = -1;           }       else { putboard();       }        }   else {       y--;       }   }```
• 01-29-2012, 12:34 AM
Jtrtoday
Re: Eight Queens Problem
its only subtracts 1 if y is greater than 8.
if y > 7 it calls putboard()

so does that mean it calls putboard when y > 7, because its done looping through?
• 01-29-2012, 12:53 AM
diamonddragon
Re: Eight Queens Problem
It calls putboard anly if y inside limits of 0 and 7 inclusive.
y never becomes 8.

It not subtracts 1 if y is > 8, but it subrtacts 1 If Queen at column y (b[y]) is NOT inside board of 8 fields