Results 1 to 7 of 7
Thread: Eight Queens Problem
 01282012, 11:24 PM #1Member
 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;
}
}
}
}
 01282012, 11:35 PM #2Senior Member
 Join Date
 Jan 2012
 Posts
 210
 Rep Power
 6
Re: Eight Queens Problem
Can You precise what is that You don't understand?
 01282012, 11:39 PM #3Member
 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?
 01292012, 12:07 AM #4Senior 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; } ...
 01292012, 12:27 AM #5Senior 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(07) ... 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; } }
 01292012, 12:34 AM #6Member
 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?
 01292012, 12:53 AM #7Senior Member
 Join Date
 Jan 2012
 Posts
 210
 Rep Power
 6
Similar Threads

How to solve the Eight Queens puzzle without recursion?
By kiregad in forum New To JavaReplies: 2Last Post: 03272010, 04:30 AM 
Need help with the Eight Queens game
By kiregad in forum New To JavaReplies: 11Last Post: 03262010, 07:50 PM 
Pruning?? (NQueens problem)
By n00neimp0rtant in forum New To JavaReplies: 1Last Post: 02142010, 07:41 AM
Bookmarks