
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flip Game II in C++
Suppose there are two players who are playing the flip game. Here we have a string that contains only these two characters: + and -, player1 and player2 take turns to flip two consecutive "++" into "--". The game ends when one player can no longer make a move and therefore the other one will be the winner. We have to define a function to check whether the starting player can guarantee a win.
So, if the input is like s = "++++", then the output will be true, as the starting player can guarantee a win by flipping the middle "++" to become "+--+".
To solve this, we will follow these steps −
Define one map memo
Define a function solve(), this will take s,
-
if s in memo, then −
return memo[s]
possible := false
n := size of s
-
for initialize i := 0, when i < n - 1, update (increase i by 1), do −
-
if s[i] is same as '+' and s[i + 1] is same as '+', then −
s[i] := '-', s[i + 1] := '-'
possible := possible OR inverse of solve(s)
s[i] := '+', s[i + 1] := '+'
-
if possible is non-zero, then −
return memo[s] := possible
-
return memo[s] := possible
From the main method do following −
return solve(s)
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: unordered_map <string, bool> memo; bool solve(string s){ if (memo.count(s)) return memo[s]; bool possible = false; int n = s.size(); for (int i = 0; i < n - 1; i++) { if (s[i] == '+' && s[i + 1] == '+') { s[i] = '-'; s[i + 1] = '-'; possible |= !solve(s); s[i] = '+'; s[i + 1] = '+'; if (possible) return memo[s] = possible; } } return memo[s] = possible; } bool canWin(string s) { return solve(s); } }; main(){ Solution ob; cout << (ob.canWin("++++")); }
Input
"++++"
Output
1