我在編碼8皇后問題時遇到了麻煩。我編了一個課程來幫助我解決問題,但由於某種原因,我做錯了一些事情。我有點理解應該發生什麼。8遞歸遞歸的非攻擊皇后算法
此外,我們必須使用遞歸來解決它,但我不知道如何使用我已閱讀過的回溯,所以我只是在檢查位置是否合法的方法中使用它。
我的板子是String [] [] board = { { "O", "O"...
等等8行8列。 如果我在概念上弄錯了什麼或者犯了嚴重的Java錯誤,請這樣說:D 謝謝!
public void solve() {
int Queens = NUM_Queens - 1;
while (Queens > 0) {
for (int col = 0; col < 8; col++) {
int row = -1;
boolean c = false;
while (c = false && row < 8) {
row ++;
c = checkPos (row, col);
}
if (c == true) {
board[row][col] = "Q";
Queens--;
}
else
System.out.println("Error");
}
}
printBoard();
}
// printing the board
public void printBoard() {
String ret = "";
for (int i = 0; i < 8; i++) {
for (int a = 0; a < 8; a++)
ret += (board[i][a] + ", ");
ret += ("\n");
}
System.out.print (ret);
}
// checking if a position is a legitimate location to put a Queen
public boolean checkPos (int y, int x) {
boolean r = true, d = true, u = true, co = true;
r = checkPosR (y, 0);
co = checkPosC (0, x);
int col = x;
int row = y;
while (row != 0 && col != 0) { //setting up to check diagonally downwards
row--;
col--;
}
d = checkPosDD (row, col);
col = x;
row = y;
while (row != 7 && col != 0) { //setting up to check diagonally upwards
row++;
col--;
}
d = checkPosDU (row, col);
if (r = true && d = true && u = true && co = true)
return true;
else
return false;
}
// checking the row
public boolean checkPosR (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && x == 7)
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y, x+1);
}
// checking the column
public boolean checkPosC (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && y == 7)
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y+1, x);
}
// checking the diagonals from top left to bottom right
public boolean checkPosDD (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && (x == 7 || y == 7))
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y+1, x+1);
}
// checking the diagonals from bottom left to up right
public boolean checkPosDU (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && (x == 7 || y == 0))
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y-1, x+1);
}
}
由於每行只能有一個皇后,所以將棋盤表示爲int [8],其中每個條目都是該行皇后的列位置。這將簡化很多事情。 – NPE 2013-03-05 08:44:33
你得到的輸出/錯誤是什麼? – Aashray 2013-03-05 08:46:02
您是否遇到任何代碼問題。預期產出是多少?您獲得的實際產出是多少? – Jayamohan 2013-03-05 08:46:14