0
處理N皇后問題。有一些難以正確填滿堆棧。希望任何人都可以給我任何指示。N-Queens,Java使用LinkedList堆棧
現在我的輸出很奇怪..只有7個節點,但是我的'成功'布爾值需要8才能成立。當我認爲它應該是1,2時,頭節點是2,1,因爲我會增加列。
我知道我需要檢查對角線,但我正在一步一步來。
我需要解決的第一件事情,如果我的conflictCheck方法。它永遠不會返回真實(因爲,是的,有衝突)。如果我弄清楚什麼,我會盡快更新。
Hurray
8, 1
7, 1
6, 1
5, 1
4, 1
3, 1
2, 1
編輯:
我做了一些修改的代碼更遞歸的嘗試。 我的新的輸出是這樣的:
The stack
1, 1
End of stack
Pushing next node
The stack
2, 1
1, 1
End of stack
Moving over one column
The stack
2, 2
1, 1
End of stack
problem
Moving over one column
The stack
2, 3
1, 1
End of stack
這是前進中的代碼/工作的一部分。現在,它的運行成一個死循環,最有可能從一段時間(conflictCheck)
public static boolean conflictCheck() {
QueenNode temp = head;
//walk through stack and check for conflicts
while(temp!=null) {
//if there is no next node, there is no conflict with it
if (temp.getNext() == null){
System.out.println("No next node");
if (queens.size() < 8) {
return false;
}
}
else if (temp.getRow() ==temp.getNext().getRow() || temp.getColumn() == temp.getNext().getColumn() ||
diagonal(temp, temp.getNext())){
return true;
}
}
return false;
}
public static void mover(QueenNode n) {
System.out.println("Moving over one column");
n.setColumn(n.getColumn()+1);
queens.viewPieces();
}
public static void playChess(int k, int total) {
QueenNode temp= head;
while (temp != null) {
System.out.println("Pushing next node");
queens.push(k,1);
queens.viewPieces();
//success
if(k == 8){
System.out.println("Hurray");
success = true;
return;
}
//conflict between pieces, loops through entire board
while (conflictCheck()) {
if (head.getColumn() != 8) {
mover(head);
}
else {
queens.pop();
mover(head);
}
}
playChess(k+1, total);
}
}
public static void main(String[] args) {
queens.push(1, 1);
queens.viewPieces();
success = false;
playChess(2, total);
}
}
當然,但這些都應該標記爲衝突? – jackie 2012-03-27 11:54:06
我做了一些編輯 – jackie 2012-03-27 12:32:39
我做了一些編輯,我試圖弄清楚如何處理衝突。如果發生衝突並且頂部的列爲8,那麼您希望將其彈出並將下一個頂部的列向上移動1.如果列不是8,則只需將頂部的列向上移動1並重新檢查衝突。現在,我有一個永恆的循環:/ – jackie 2012-03-27 12:38:01