Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- bool canMeasureWater(int J1, int J2, int T) {
- // Check for invalid inputs
- if (J1 + J2 < T) {
- return false;
- }
- // Create a queue to hold the current state of the jugs
- queue<pair<int, int>> q;
- // Push the initial state of the jugs (both empty) onto the queue
- q.push({0, 0});
- // Create a set to hold the visited states
- set<pair<int, int>> visited;
- // Mark the initial state as visited
- visited.insert({0, 0});
- // While the queue is not empty
- while (!q.empty()) {
- // Get the current state of the jugs
- auto currState = q.front();
- q.pop();
- // If either jug has T units of water, return true
- if (currState.first == T || currState.second == T || currState.first+currState.second==T) {
- return true;
- }
- // Fill the first jug
- if (visited.find({J1, currState.second}) == visited.end()) {
- q.push({J1, currState.second});
- visited.insert({J1, currState.second});
- }
- // Fill the second jug
- if (visited.find({currState.first, J2}) == visited.end()) {
- q.push({currState.first, J2});
- visited.insert({currState.first, J2});
- }
- // Empty the first jug
- if (visited.find({0, currState.second}) == visited.end()) {
- q.push({0, currState.second});
- visited.insert({0, currState.second});
- }
- // Empty the second jug
- if (visited.find({currState.first, 0}) == visited.end()) {
- q.push({currState.first, 0});
- visited.insert({currState.first, 0});
- }
- // Pour water from the first jug into the second jug
- int SpaceInJ2 = J2 - currState.second;
- if (currState.first >= SpaceInJ2) {
- int remainingInJ1 = currState.first - SpaceInJ2;
- if (visited.find({remainingInJ1, J2}) == visited.end()) {
- q.push({remainingInJ1, J2});
- visited.insert({remainingInJ1, J2});
- }
- }
- else if (visited.find({0, currState.first + currState.second}) == visited.end()) { // Not enough water in J2 to fill completely
- q.push({0, currState.first + currState.second});
- visited.insert({0, currState.first + currState.second});
- }
- // Pour water from the second jug into the first jug
- int SpaceInJ1 = J1 - currState.first;
- if (currState.second >= SpaceInJ1) {
- int remainingInJ2 = currState.second - SpaceInJ1;
- if (visited.find({J1, remainingInJ2}) == visited.end()) {
- q.push({J1, remainingInJ2});
- visited.insert({J1, remainingInJ2});
- }
- }
- else if (visited.find({currState.first + currState.second, 0}) == visited.end()) { // Not enough water in J1 to fill completely
- q.push({currState.first + currState.second, 0});
- visited.insert({currState.first + currState.second, 0});
- }
- }
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment