我正在使用此處找到的 Alpha-Beta 修剪示例來研究 Minimax 算法。在示例中,他們使用數組來實現搜索樹。我遵循了這個例子,但也嘗試用二叉搜索樹來實現它。以下是我在樹中使用的值:3、5、6、9、1、2、0、-1。最后的最佳值應該是 5。使用 BST 實現,我一直得到 2。我認為這是問題所在,但我不知道如何解決它:如果在嘗試檢查下一個值時看到葉節點停止獲取空指針異常,我編寫了代碼以退出遞歸。但是相反,我認為它過早地停止搜索(基于我在使用調試器單步執行代碼時看到的內容)。但是,如果我刪除檢查,則代碼會在空指針上失敗。有人可以指出我正確的方向嗎?我究竟做錯了什么?這是代碼:public class AlphaBetaMiniMax { private static BinarySearchTree myTree = new BinarySearchTree(); static int MAX = 1000; static int MIN = -1000; static int opt; public static void main(String[] args) { //Start constructing the game AlphaBetaMiniMax demo = new AlphaBetaMiniMax(); //3, 5, 6, 9, 1, 2, 0, -1 demo.myTree.insert(3); demo.myTree.insert(5); demo.myTree.insert(6); demo.myTree.insert(9); demo.myTree.insert(1); demo.myTree.insert(2); demo.myTree.insert(0); demo.myTree.insert(-1); //print the tree System.out.println("Game Tree: "); demo.myTree.printTree(demo.myTree.root); //Print the results of the game System.out.println("\nGame Results:"); //run the minimax algorithm with the following inputs int optimalVal = demo.minimax(0, myTree.root, true, MAX, MIN); System.out.println("Optimal Value: " + optimalVal); } /** * @param alpha = 1000 * @param beta = -1000 * @param nodeIndex - the current node * @param depth - the depth to search * @param maximizingPlayer - the current player making a move * @return - the best move for the current player */ public int minimax(int depth, MiniMaxNode nodeIndex, boolean maximizingPlayer, double alpha, double beta) { //Base Case #1: Reached the bottom of the tree if (depth == 2) { return nodeIndex.getValue(); } } }}輸出:Game Tree: -1 ~ 0 ~ 1 ~ 2 ~ 3 ~ 5 ~ 6 ~ 9 ~ Game Results:Optimal Value: 2
1 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
您的問題是您的迭代取決于 2 的循環控制,而不是 node== null 查找 nodeIndex.getRight()(for max) getLeft(for min.)
記住一棵樹有 1 個頭(第一級)
第二級 = 2
第 3 級 = 4
4日8等。所以你的循環算法甚至不會下降 3 個級別。
for (int i = 0; i < 2; i++) {
int val = minimax(depth + 1, nodeIndex.getLeft(), false, alpha, beta);
best = Math.max(best, val);
alpha = Math.max(alpha, best);
//Alpha Beta Pruning
if (beta <= alpha) {
break;
}
更改循環以正確控制迭代,您應該很容易找到最高值。
添加回答
舉報
0/150
提交
取消