Optimising Minimax for a Game

129 Views Asked by At

I'm currently trying to solve a programming problem using minimax with alpha-beta-pruning. The game is represented as a tree with a defined root. Each node has a given cost. Each node can have an amount of childs bigger than 0 if its not a leaf. The game has to end at a leaf.

Player A wants to maximize the cost he can receive by traversing the tree. He can choose to stay at the current node, or go to one of its childs. Player B wants to minimize the cost, but he has to choose a child and can't pass unlike Player A. Both Players play optimally.

I have implemented a solution, which does return the desired results, but is too slow after a certain amount of nodes, leading to a timeout. My idea would be to somehow save the results of the previous minimax search for the given tree, but that only helps if Player A chooses to advance, otherwise I would have to do the minimax search again.

vector<int> edges[MAXN];
int minimax(int node, bool p1_turn, int alpha, int beta) {
    if(edges[node].empty()) return cost[node];

    if(p1_turn) {
        int best = minimax(node, false, alpha, beta);
        for(auto u: edges[node]) {
            int val = minimax(u, false, alpha, beta);
            best = max(val, best);
            alpha = max(alpha, best);

            if(beta <= alpha) {
                break;
            } 
        
        }
        return best;
    } else {
        int best = MAX_INF;
        for(auto u: edges[node]){
            int val = minimax(u, true, alpha, beta);
            best = min(best, val);
            beta = min(best, beta);

            if(beta <= alpha){
                break;
            }
        }
        return best;
    }
}


...
minimax(1, true, MIN_INF, MAX_INF)
...

Applying the above algorithm returns the desired results, but is too slow after a certain amount of nodes.

EDIT

Changed the inner if-block to be more in line with https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning#Pseudocode

    if(edges[node].empty()) return cost[node];
    if(p1_turn) {
        int best = minimax(node, false, alpha, beta);
        for(auto u: edges[node]) {
            best = max(best, minimax(u, false, alpha, beta));
            if(best > beta) {
                break;
            }
            alpha = max(alpha, best);        
        }
        return best;
    } else {
        int best = MAX_INF;
        for(auto u: edges[node]){
            best = min(best, minimax(u, true, alpha, beta));
            if(best < alpha){
                break;
            }
            beta = min(best, beta);
        }
        return best;
    }
0

There are 0 best solutions below