VOOZH about

URL: https://www.geeksforgeeks.org/dsa/predict-the-winner-of-the-game-sprague-grundy/

⇱ Predict the winner of the game | Sprague-Grundy - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Predict the winner of the game | Sprague-Grundy

Last Updated : 11 Jul, 2025

Given a 4x4 binary matrix. Two players A and B are playing a game, at each step a player can select any rectangle with all 1's in it and replace all 1's with 0. The player that cannot select any rectangle loses the game. Predict the winner of the game assuming that they both play the game optimally and A starts the game. Examples:

Input : 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 
Output : A Step 1: Player A chooses the rectangle with a single one at position (1, 2), so the new matrix becomes 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 Step 2: Player B chooses the rectangle with a single one at position (1, 3), so the new matrix becomes 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 Step 3: Player A chooses the rectangle with a single one at position (4, 4), so the new matrix becomes 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Step 4: Player B cannot move, hence A wins the game. 

Input : 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 
Output : B

Approach: The problem can be solved using the sprague-grundy theorem. The base case for Sprague-Grundy is Grundy[0] = 0, which is all the positions in the matrix are filled with 0, then B wins it, hence 0. In grundy, recursively we call grundy function with all the states that are possible. The 4x4 matrix can be represented as a binary 16-bit number which is 65535 in int, where every bit represents the position in a matrix. Below are the steps to solve the above problem.

  • Convert the matrix into int val.
  • Call the recursive function with val that generates the grundy value using memoization.
  • Inside the recursive function, all the grundy states can be visited by generating all possible rectangles(using four for loops).
  • Check the generated rectangle, if it is a rectangle of the matrix. Then this is a state to be visited by grundy.
  • To get Grundy value using MEX, please see this.
  • If the recursion return 0, then player B wins, else player A wins.

Below is the implementation of the above approach 


Output
Player A wins

Time Complexity: O(N2), we are using recursion which will cost us O(81*N) and we are also using nested loops to traverse the matrix which will cost us O(N*N) time.
Auxiliary Space: O(N2), we are using extra space for the array grundy which will be of size N*N in the worst case.

Comment
Article Tags: