488. Zuma Game

来源:互联网 发布:淘宝上找货源 编辑:程序博客网 时间:2024/05/19 03:44

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.

Examples:
Input: "WRRBBW", "RB"Output: -1Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WWInput: "WWRRBBWW", "WRBRW"Output: 2Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> emptyInput:"G", "GGGGG"Output: 2Explanation: G -> G[G] -> GG[G] -> empty Input: "RBYYBBRRB", "YRBGB"Output: 3Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty

Note:

  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. The number of balls on the table won't exceed 20, and the string represents these balls is called "board" in the input.
  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. Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.


思路:因为是求最小的次数,考虑用BFS
BFS,因为不能重复使用,所以还要维护一个额外的hand变量
这样放到queue里面的就得是个class对象了

其实DFS也可以,当全部都消掉后返回就好了
DFS prune还是TLE
应该从递归上进行优化,不要一个位置一个位置的乱插,要有目的性的插入
要插在能消除的位置上,想想要是自己玩这个游戏,应该也是这样做

public class Solution {int min = Integer.MAX_VALUE;Map<Character, Integer> map = new HashMap<Character, Integer>();    public int findMinStep(String board, String hand) {    for(char c : "RYBGW".toCharArray())map.put(c, 0);    for(char c : hand.toCharArray())map.put(c, 1+map.get(c));    min = hand.length() + 1;    dfs(board, 0);    return min == hand.length() + 1 ? -1 : min;    }private void dfs(String board, int step) {if(step >= min)return;if("".equals(board)) {min = Math.min(min, step);return;}for(int i=0; i<board.length(); i++) {int j = i + 1;while(j<board.length() && board.charAt(j)==board.charAt(i))j++;int needToDismiss = 3 - (j-i);char c = board.charAt(i);if(map.get(c) >= needToDismiss) {map.put(c, map.get(c)-needToDismiss);dfs(process(board.substring(0, i)+board.substring(j)), step+needToDismiss);map.put(c, map.get(c)+needToDismiss);}}}public String process(String s) {while(true) {StringBuilder sb = new StringBuilder();for(int i=0; i<s.length(); i++) {int j = i+1;while(j<s.length() && s.charAt(j)==s.charAt(i))j++;if(j-i < 3)sb.append(s.substring(i, j));i = j - 1;// i++还会加回去}if(s.equals(sb.toString()))break;s = sb.toString();}return s;}}


原创粉丝点击