|
| 1 | +function canMeasureWater(jug1Capacity, jug2Capacity, targetAmount) { |
| 2 | + // Base case: If the target amount is greater than the sum of both jugs, it's not possible. |
| 3 | + if (targetAmount > jug1Capacity + jug2Capacity) return false; |
| 4 | + |
| 5 | + // Use BFS to explore possible states. |
| 6 | + let visited = new Set(); // To keep track of visited states. |
| 7 | + let queue = [[0, 0]]; // Starting with both jugs empty. |
| 8 | + |
| 9 | + while (queue.length > 0) { |
| 10 | + let [jug1, jug2] = queue.shift(); |
| 11 | + |
| 12 | + // If we've reached the target amount in either jug. |
| 13 | + if (jug1 === targetAmount || jug2 === targetAmount || jug1 + jug2 === targetAmount) { |
| 14 | + return true; |
| 15 | + } |
| 16 | + |
| 17 | + // If this state has been visited, skip it. |
| 18 | + let state = `${jug1},${jug2}`; |
| 19 | + if (visited.has(state)) continue; |
| 20 | + visited.add(state); |
| 21 | + |
| 22 | + // Add all possible next states to the queue: |
| 23 | + queue.push([jug1Capacity, jug2]); // Fill Jug 1 |
| 24 | + queue.push([jug1, jug2Capacity]); // Fill Jug 2 |
| 25 | + queue.push([0, jug2]); // Empty Jug 1 |
| 26 | + queue.push([jug1, 0]); // Empty Jug 2 |
| 27 | + queue.push([Math.max(0, jug1 - (jug2Capacity - jug2)), Math.min(jug2Capacity, jug1 + jug2)]); // Pour Jug 1 into Jug 2 |
| 28 | + queue.push([Math.min(jug1Capacity, jug1 + jug2), Math.max(0, jug2 - (jug1Capacity - jug1))]); // Pour Jug 2 into Jug 1 |
| 29 | + } |
| 30 | + |
| 31 | + // If no solution is found |
| 32 | + return false; |
| 33 | +} |
| 34 | + |
0 commit comments