Basically I place a queen on a square, go to the next row and try to place a queen on that square, if there is a queen on the same row, column or diagonal as the square I am trying to put a queen on, I go to the next column. If I get to the end of the row without placing a queen, I go back a row and remove a queen and try to put it somewhere else.
This works and isn't very complicated to code, my solution is:
package ss12;
/**
*
* @author James
*/
public class e7 {
public static int[] DX = {1,1,-1,-1};
public static int[] DY = {-1,1,1,-1};
public static void main(String[] args) {
char[][] arcQueens = new char[8][8];
for (int i=0;i<8;i++) {
for (int x=0;x<8;x++) {
arcQueens[i][x] = '.';
}
}
if(tryQueen(arcQueens,8,0)) {
display(8,arcQueens);
}
}
public static boolean tryQueen(char[][] arcQueens, int nSize, int nRow) {
if (nRow >= nSize) {
return true; // we have gotten to the last row so stop
}
boolean sol;
for (int col=0;col<nSize;col++) {
if (!checkConflict(arcQueens,nSize,nRow,col)) {
arcQueens[nRow][col] = 'q';
sol = tryQueen(arcQueens,nSize,nRow+1);
if (sol) {
return true; // we were successfully able to place a piece
} else {
arcQueens[nRow][col] = '.'; // an error has occured so don't place queen
}
}
}
return false;
}
public static boolean checkConflict(char[][] arcBoard, int nSize, int nRow, int nCol) {
// check row for a queen
// check col for a queen
// check diagonal for a queen
for (int i=0;i<nSize;i++) {
if (arcBoard[nRow][i] == 'q') {
return true; // there is a queen in the same row as the piece we tried to place
}
}
for (int i=0;i<nSize;i++) {
if (arcBoard[i][nCol] == 'q') {
return true;// there is a queen in the same col as the piece we tried to place
}
}
// check if there is a conflict on a diagonal
for (int nDir=0;nDir<4;nDir++) {
if (isDiagonalConflict(arcBoard,nDir,nRow,nCol)) {
return true;
}
}
return false;
}
public static void display(int nSize, char[][] arcBoard) {
for (int i=0;i<nSize;i++) {
for (int x=0;x<nSize;x++) {
System.out.print(arcBoard[i][x] + " ");
}
System.out.println();
}
}
public static boolean isDiagonalConflict(char[][] arcBoard, int nDir, int x, int y) {
if(x < 0 || x >= arcBoard.length || y < 0 || y >= arcBoard[0].length) {
return false;
}
if (arcBoard[x][y] == 'q') {
return true;
}
return isDiagonalConflict(arcBoard,nDir,x+DX[nDir],y+DY[nDir]);
}
}
This gives me one solution, but I'm completely stuck as to how I can generate all solutions for this problem. If someone can give me a pointer for something that can help, that would be great. :) I was maybe thinking it has something to do with graphs? I know how backtracking works but I don't get how to count all solutions for some problem?
Any suggestions would be great. Thanks!


Sign In
Create Account


Back to top









