1. Member Join Date
Nov 2011
Posts
15
Rep Power
0

## 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;
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 = -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--;
}
}
}
}  Reply With Quote

2. Senior Member Join Date
Jan 2012
Posts
210
Rep Power
9

## Re: Eight Queens Problem

Can You precise what is that You don't understand?  Reply With Quote

3. Member Join Date
Nov 2011
Posts
15
Rep Power
0

## 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?  Reply With Quote

4. Senior Member Join Date
Jan 2012
Posts
210
Rep Power
9

## Re: Eight Queens Problem

What is this part of code doing?

Java Code:
```
if (y < 7) {
b[++y] = -1;
} ...```  Reply With Quote

5. Senior Member Join Date
Jan 2012
Posts
210
Rep Power
9

## Re: Eight Queens Problem

As I understood this part, it says:

Java 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.```

Java 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--;
}
}```  Reply With Quote

6. Member Join Date
Nov 2011
Posts
15
Rep Power
0

## 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?  Reply With Quote

7. Senior Member Join Date
Jan 2012
Posts
210
Rep Power
9

## 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
Last edited by diamonddragon; 01-28-2012 at 11:57 PM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•