488 Zuma Game

488. Zuma Game

1. Question

hink about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.
Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.
Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.
1
Examples:
2
3
Input: "WRRBBW", "RB"
4
Output: -1
5
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW
6
7
Input: "WWRRBBWW", "WRBRW"
8
Output: 2
9
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty
10
11
Input:"G", "GGGGG"
12
Output: 2
13
Explanation: G -> G[G] -> GG[G] -> empty
14
15
Input: "RBYYBBRRB", "YRBGB"
16
Output: 3
17
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty
Copied!
Note:
  1. 1.
    You may assume that the initial row of balls on the table won’t have any 3 or more consecutive balls with the same color.
  2. 2.
    The number of balls on the table won't exceed 20, and the string represents these balls is called "board" in the input.
  3. 3.
    The number of balls in your hand won't exceed 5, and the string represents these balls is called "hand" in the input.
  4. 4.
    Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.

2. Implementation

(1) DFS
1
class Solution {
2
public int findMinStep(String board, String hand) {
3
int[] count = new int[256];
4
5
for (char c : hand.toCharArray()) {
6
++count[c];
7
}
8
9
return getMinStepByDFS(board, count);
10
}
11
12
public int getMinStepByDFS(String board, int[] count) {
13
if (board.length() == 0) {
14
return 0;
15
}
16
17
int res = Integer.MAX_VALUE;
18
19
int i = 0;
20
int j = 0;
21
22
while (i < board.length()) {
23
while (j < board.length() && board.charAt(i) == board.charAt(j)) {
24
++j;
25
}
26
27
char color = board.charAt(i);
28
int balls = 3 - (j - i);
29
30
if (count[color] >= balls) {
31
String newBoard = collapse(board.substring(0, i) + board.substring(j));
32
count[color] -= balls;
33
34
int steps = getMinStepByDFS(newBoard, count);
35
36
if (steps >= 0) {
37
res = Math.min(res, steps + balls);
38
}
39
40
count[color] += balls;
41
}
42
i = j;
43
}
44
return res == Integer.MAX_VALUE ? -1 : res;
45
}
46
47
public String collapse(String board) {
48
int i = 0;
49
50
while (i < board.length()) {
51
int j = i;
52
while (j < board.length() && board.charAt(i) == board.charAt(j)) {
53
++j;
54
}
55
56
if (j - i >= 3) {
57
board = board.substring(0, i) + board.substring(j);
58
i = 0;
59
}
60
else {
61
++i;
62
}
63
}
64
return board;
65
}
66
}
Copied!

3. Time & Space Complexity

DFS: 时间复杂度: O((m + n)^m * n^2), m是board的长度,n是hand的长度, 空间复杂度: O(mn)

4. References