1. Minimax Recursive Search
Intuition
Recursively evaluate whether the current player can force a win by checking if any move forces the opponent to lose.
Algorithm
- Define
canWin(rem). - If
rem == 0, return false. - If
!canWin(rem - 1), return true. - If
rem >= xand!canWin(rem - x), return true. - If
rem >= yand!canWin(rem - y), return true. - Return false.
#include <iostream> using namespace std; bool canWinRec(int rem, int x, int y) { if (rem == 0) return false; if (!canWinRec(rem - 1, x, y)) return true; if (rem >= x && !canWinRec(rem - x, x, y)) return true; if (rem >= y && !canWinRec(rem - y, x, y)) return true; return false;} int main() { int n = 5, x = 3, y = 4; cout << "Player A wins (Recursive): " << (canWinRec(n, x, y) ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(3^n) - Space complexity:
O(n) recursion call stack