头条笔试题 三桶水凑出指定体积水

试题
头条笔试题 三桶水凑出指定体积水_第1张图片

代码
考虑从上一状态转换到下一状态有三种方法:
1、往某个桶加水
2、倒掉某桶的水
3、将一个桶的水往另一个桶里倒

使用宽度优先搜索:
1、一旦找到结果必然是最优结果,求解最少次数。
2、有助剪枝,当log中保存的状态一旦已经尝试过肯定无需继续尝试。

import java.util.*;

class Main{
    public static void main(String[] args){
        int[] bucket = new int[3];
        int[] water = new int[]{3, 5, 8};
        int target = 4;
        int step = 0;
        int[][] shift = new int[][]{
                {0,1},{0,2},
                {1,0},{1,2},
                {2,0},{2,1},
        };
        HashSet log = new HashSet<>();
        Queue queue = new LinkedList<>();
        queue.offer(bucket);

        while(!queue.isEmpty()){
            int size = queue.size();
            for(int q=0; q

你可能感兴趣的:(LeetCode,LeetCode面试常见试题)