Think about Zuma Game. You have a row of balls on the table, colored red®, 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.
Examples:
Input: “WRRBBW”, “RB”
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW
Input: “WWRRBBWW”, “WRBRW”
Output: 2
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty
Input:“G”, “GGGGG”
Output: 2
Explanation: G -> G[G] -> GG[G] -> empty
Input: “RBYYBBRRB”, “YRBGB”
Output: 3
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty
祖玛游戏,相同颜色的球超过3个时消去,问消去所有的球所需要投出去的球数,如果用完手上的球后仍有球存在,则输出-1。
思路:
只考虑把球投到相同颜色的后面这种情况,每次检查相同颜色达到3个需要投几个球,如果有则投出去,然后update消去后的情况,注意可以发生连锁消去。然后用消去后的球重复上面的动作,也就是DFS。
手上的球颜色顺序因为不同,所以用一个HashMap统计每种颜色有几个球,投出去后在相应的颜色减去数量。
public int findMinStep(String board, String hand) {
if (board == null || board.length() == 0) {
return 0;
}
if (hand == null || hand.length() == 0) {
return -1;
}
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < hand.length(); i++) {
map.put(hand.charAt(i),map.getOrDefault(hand.charAt(i), 0) + 1);
}
return dfs(board, map);
}
public int dfs(String board, HashMap<Character, Integer> hand) {
if (board.length() == 0) {
return 0;
}
int result = Integer.MAX_VALUE;
int i = 0;
int j = 0;
while(i < board.length()) {
while(j < board.length() && board.charAt(j) == board.charAt(i)) {
j ++;
}
char color = board.charAt(i);
int needed = 3 - (j - i);
if (hand.getOrDefault(color, 0) >= needed) {
String afterErase = update(board.substring(0, i) +
board.substring(j));
hand.put(color, hand.get(color) - needed);
int tmp = dfs(afterErase, hand);
if (tmp >= 0) {
result = Math.min(result, tmp + needed);
}
hand.put(color, hand.get(color) + needed);
}
i = j;
}
return (result == Integer.MAX_VALUE) ? -1 : result;
}
public String update(String board) {
if (board.length() == 0) {
return "";
}
int i = 0;
int j = 0;
while(i < board.length()) {
j = i;
while (j < board.length() && board.charAt(j) == board.charAt(i)) {
j ++;
}
if (j - i >= 3) {
board = board.substring(0, i) + board.substring(j);
i = 0;
} else {
i = j;
}
}
return board;
}