我試圖完成我的家庭作業項目,並尋求幫助找到一個錯誤。我正在使用回溯算法來查找N皇后問題的所有解決方案。我主要關心的是我的衝突方法 - 它在堆棧類中。其目的是檢測傳遞的Queen對象(衝突方法的參數1)是否與板上的任何其他女王/王后在同一行,列或對角線上。傳遞給衝突方法的queen對象存儲在Queen類中,並且在Point類的實例的幫助下記錄它的位置。我的代碼在我創建的Queen類中使用了兩個方法,public int getRow()和public int getColumn()。兩者都返回一個int。第二個參數是一個名爲board的二維數組(或數組)。皇后已經在棋盤上用這個布爾值表示真值。布爾值爲false表示板上有空的方塊。N皇后使用堆棧,找不到bug
Solution.n是對另一個類中的靜態int變量的引用。它的值表示板的邊緣。示例...對於8皇后問題,我們創建一個大小爲8的二維數組。Solution.n遞減1以等於二維數組的最後一個索引。
下面是代碼:
public boolean conflict(Queen x, boolean [][] board) //conflict method
{
if(checkColumn(x, board) == false)
return true; //conflict
else if(checkRow(x, board) == false)
return true; //conflict
else if(checkDiagonal(x, board) == false)
return true; //conflict
else
return false; //no conflict on board
}
private boolean checkColumn(Queen x, boolean [][] board)//returns true when column is safe
{
int col = x.getColumn();
for(int row = 0; row <= Solution.n; row++)
{
if(board[row][col] == true) //queen is in this column
{
return false;
}
}
return true;
}
private boolean checkRow(Queen x, boolean [][] board) //returns true when row is safe
{
int row = x.getRow();
for(int col = 0; col <= Solution.n; col++)
{
if(board[row][col] == true) //queen is in this row
{
return false;
}
}
return true;
}
private boolean checkDiagonal(Queen location, boolean [][] board) //returns true when diagonal is safe
{
int row, col;
row = location.getRow() - 1;
col = location.getColumn() - 1;
while(row >=0 && col >= 0) //iterate down-left
{
if(board[row][col] == true) //queen found?
{
return false;
}
row--;
col--;
}
row = location.getRow() - 1;
col = location.getColumn() + 1;
while(row != -1 && col <= Solution.n) //iterate down-right
{
if(board[row][col] == true) //queen found?
{
return false;
}
row--;
col++;
}
row = location.getRow() + 1;
col = location.getColumn() + 1;
while(row <= Solution.n && col <= Solution.n) //iterate up-right
{
if(board[row][col] == true) //queen found?
{
return false;
}
row++;
col++;
}
row = location.getRow() +1;
col = location.getColumn()-1;
while(row <= Solution.n && col != -1) //iterate up-left
{
if(board[row][col] == true) //queen found?
{
return false;
}
row++;
col--;
}
return true;
}
我相信這個片段的代碼包含一個錯誤,但如果我錯了,然後我爲浪費你的時間道歉:P
你的幫助將是不勝感激。謝謝! :D
如果可以,請發佈剩餘的代碼。我花了幾分鐘時間查看它,沒有發現任何東西跳出來。一些循環有點奇怪,但沒有看起來不起作用。 – jedwards
你不說它是如何失敗? –