![]() |
VOOZH | about |
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.
Below is the implementation of the above approach
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.