Zuma Game

This page explains Java solution to problem Zuma Game using Backtracking.

Problem Statement

Think 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.

Example 1:

Input: board = "WRRBBW", hand = "RB"
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW

Example 2:

Input: board = "WWRRBBWW", hand = "WRBRW"
Output: 2
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty

Solution

If you have any suggestions in below code, please create a pull request by clicking here.

package com.vc.hard;

import java.util.*;

class ZumaGame {
    public int findMinStep(String board, String hand) {
        HashMap<Character, Integer> handMap = new HashMap<>();
        for(int i = 0; i < hand.length(); i++) {
            char ch = hand.charAt(i);
            handMap.put(ch, handMap.getOrDefault(ch, 0) + 1);
        }
        int res = helper(board, handMap);
        return res == Integer.MAX_VALUE ? -1 : res;
    }

    private int helper(String board, HashMap<Character, Integer> handMap) {
        if(board.length() == 0) return 0;
        else if(handMap.size() == 0) return Integer.MAX_VALUE;
        else {
            int resMin = Integer.MAX_VALUE;
            for(int index = 0; index < board.length(); index++) {
                int to = index;
                char requiredChar = board.charAt(to);
                while(to < board.length() && board.charAt(to) == requiredChar) to++;
                int length = to - index;
                int requiredLength = Math.max(3 - length, 0);
                if(requiredLength == 0 || handMap.getOrDefault(requiredChar, 0) >= requiredLength) {
                    String newBoard = board.substring(0, index) + board.substring(to);
                    handMap.put(requiredChar, handMap.getOrDefault(requiredChar, 0) - requiredLength);
                    int resInternal = helper(newBoard, handMap);
                    if(resInternal != Integer.MAX_VALUE) {
                        resMin = Math.min(resMin, resInternal + requiredLength);
                    }
                    handMap.put(requiredChar, handMap.getOrDefault(requiredChar, 0) + requiredLength);
                }
            }
            return resMin;
        }
    }
}

Time Complexity

O(2N) Where
N is length of input string board

Space Complexity

O(M) Where
M is length of input string hand