[LeetCode] Zuma Game

488. Zuma Game

You are playing a variation of the game Zuma.

In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red ‘R’, yellow ‘Y’, blue ‘B’, green ‘G’, or white ‘W’. You also have several colored balls in your hand.

Your goal is to clear all of the balls from the board. On each turn:

  • Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.
  • If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board.
  • If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.
  • If there are no more balls on the board, then you win the game.
  • Repeat this process until you either win or do not have any more balls in your hand.

Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
unordered_map<char, int> freq;
unordered_map<string, long long> vis;
string serialize() {
string res = "";
for(auto& [ch, cnt] : freq) {
res += string(cnt, ch);
}
return res;
}
string update(string s) {
int n = s.length(), l = 0, r = 0;
while(r < n) {
while(r < n and s[l] == s[r]) r++;
if(r - l >= 3) {
return update(s.substr(0,l) + s.substr(r));
}
l = r;
}
return s;
}
long long dfs(string& s) {
if(s.length() == 0) return 0;
string key = s + '#' + serialize();
if(vis.count(key)) return vis[key];
long long& res = vis[key] = INT_MAX;
for(auto& [ch, cnt] : freq) {
if(!cnt) continue;
for(int i = 0; i < s.length(); i++) {
if((i and s[i-1] == s[i] and s[i] != ch) or (s[i] == ch)) {
if(s[i] == ch and i and s[i-1] == s[i]) continue;
cnt--;

auto ns = update(s.substr(0,i) + string(1,ch) + s.substr(i));
res = min(res, 1 + dfs(ns));

cnt++;
}
}
}

return res;
}
public:
int findMinStep(string board, string hand) {
for(auto& h : hand) freq[h]++;
long long res = dfs(board);
return res > hand.length() ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/19/PS/LeetCode/zuma-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.