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[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--;
}
}
}
}

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

## Re: Eight Queens Problem

Can You precise what is that You don't understand?

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?

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

## Re: Eight Queens Problem

What is this part of code doing?

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

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

## 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--;
}
}```

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?

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

## 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-29-2012 at 12:57 AM.

#### Posting Permissions

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