Water And Jug Problem Problem


Description

LeetCode Problem 365.

You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.

If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.

Operations allowed:

  • Fill any of the jugs with water.
  • Empty any of the jugs.
  • Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.

Example 1:

1
2
3
Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
Output: true
Explanation: The famous <a href="https://www.youtube.com/watch?v=BVtQNK_ZUJg&amp;ab_channel=notnek01" target="_blank">Die Hard</a> example 

Example 2:

1
2
Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
Output: false

Example 3:

1
2
Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
Output: true

Constraints:

  • 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 10^6


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
        
        int x = jug1Capacity, y = jug2Capacity, z = x + y;
        int steps[] = {x, -x, -y, y}; 
        
        queue<int> q;
        vector<int> vis(z + 1, 0); 
        q.push(0);
        vis[0] = 1;
        while (!q.empty()) {
            int node = q.front();
            q.pop();
            
            if (node == targetCapacity) {
                return true; 
            }
            for (int i = 0; i < 4; i++) {
                int newNode = node + steps[i];
                if (newNode >= 0 && newNode <= z && vis[newNode] == 0) {
                    q.push(newNode);
                    vis[newNode] = 1;
                }
            }
        }
        return false; 
    }
};




Related Posts

Snakes And Ladders Problem

LeetCode 909. You are given an n x n integer...

Rotting Oranges Problem

LeetCode 994. You are given an m x n grid...

Numbers With Same Consecutive Differences Problem

LeetCode 967. Return all non-negative integers of length n such...

K-Similar Strings Problem

LeetCode 854. Strings s1 and s2 are k-similar (for some...