Leetcode::Water and Jug Problem

point

Design

Bezouts identity

BFS

Big O(time)

Code

Bezouts identity

class Solution {
public:
int _gcd(int x, int y){
    if (y == 0) return x;
    return _gcd(y, x%y);
}
    bool canMeasureWater(int x, int y, int target) {
        if (x + y < target) return false;
        return (target % _gcd(x, y)) == 0;
    }
};

BFS

class Solution {
public:
    bool canMeasureWater(int x, int y, int target) {
        set<pair<int,int> > st;
        queue<pair<int,int> > que;
        st.insert({x, y});
        que.push({x, y});
        
        while(!que.empty()) {
            set<pair<int,int> > tmp;
            int a = que.front().first, b = que.front().second;
            que.pop();

            if (a + b == target) return true;
            tmp.insert({x, b});
            tmp.insert({0, b});
            tmp.insert({a, y});
            tmp.insert({a, 0});
            tmp.insert({0, 0});
            tmp.insert({x, y});
            if (a + b <= x) tmp.insert({a + b, 0});
            else tmp.insert({x, (a+b) - x});

            if (a + b <= y) tmp.insert({0, a + b});
            else tmp.insert({(a+b) - y, y});

            for(auto cur = tmp.begin(); cur != tmp.end(); cur++) {
                if (st.find({*cur}) == st.end()) {
                    que.push({*cur});
                    st.insert(*cur);
                }
            }
            
        }
        return false;
    }
};