# 365. Water and Jug Problem

T: O(j1+j2)

S: O(j1+j2)

````java
```java
class Solution {
    public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
        int j1 = Math.min(jug1Capacity, jug2Capacity);
        int j2 = Math.max(jug1Capacity, jug2Capacity);

        boolean[] visited = new boolean[j1+j2+1];
        return dfs(j1, j2, visited, targetCapacity, 0);

    }
    private boolean dfs(int j1, int j2, boolean[] visited, int targetCapacity, int current) {
        if (current == targetCapacity) {
            return true;
        }
        if (visited[current]) {
            return false;
        }
        visited[current] = true;

        /**
        current 水量 分成三個區間

           ----j1----j2---- 


        */
        if (current <= j1) {
            return dfs(j1, j2, visited, targetCapacity, 0) || // 倒掉 j1
                dfs(j1, j2, visited, targetCapacity, j1) || // 裝滿到j1
                dfs(j1, j2, visited, targetCapacity, j2) || // 裝滿到j2
                dfs(j1, j2, visited, targetCapacity, current + j2) || //水在 j1(so current <= j1), 把j2 裝滿
                dfs(j1, j2, visited, targetCapacity, current + j1); //水在 j2(current <= j1), 把 j1 裝滿
        } else if (current <= j2) {
            return dfs(j1, j2, visited, targetCapacity, 0) || // 倒掉 j2
                dfs(j1, j2, visited, targetCapacity, current - j1) || // 水在 j1 and j2, 倒掉 j1
                dfs(j1, j2, visited, targetCapacity, j2); // 水都在 j2, 裝滿 j2
        } else {
            return dfs(j1, j2, visited, targetCapacity, 0) || // 全部倒掉
                dfs(j1, j2, visited, targetCapacity, current - j1) || // 倒掉 j1
                dfs(j1, j2, visited, targetCapacity, current - j2); // 倒掉 j2
        }
    }
}
```
````

refer this later:

<https://leetcode.com/problems/water-and-jug-problem/solutions/3290210/python-dfs-bfs-complexity-analysis-video-explanation/>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/generic-dfs/365.-water-and-jug-problem.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
