
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Jump Game II in Python
- Stone Game II in C++
- Flip to Zeros in C++
- 123 Number Flip in Python
- bitset::flip() in C++ STL
- Random Flip Matrix in C++
- Flip Equivalent Binary Trees in C++
- Flip and Invert Matrix in Python
- Flip Effect with CSS
- Hangman Game in Python?
- Jump Game in Python
- Stone Game in C++
- Baseball Game in Python
- Dungeon Game in C++
- Zuma Game in C++
