> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/graphs-bfs-and-dfs/chef-and-reversing.md).

# Chef and Reversing

Sometimes mysteries happen. Chef found a directed graph with **N** vertices and **M** edges in his kitchen!

The evening was boring and chef has nothing else to do, so to entertain himself, Chef thought about a question "What is the minimum number of edges he needs to reverse in order to have at least one path from vertex **1** to vertex **N**, where the vertices are numbered from **1** to **N**.

#### Input

Each test file contains only one test case.

The first line of the input contains two space separated integers **N** and **M**, denoting the number of vertices and the number of edges in the graph respectively. The **i**th line of the next **M** lines contains two space separated integers **Xi** and **Yi**, denoting that the **i**th edge connects vertices from **Xi** to **Yi**.

#### Output

In a single line, print the minimum number of edges we need to revert. If there is no way of having at least one path from **1** to **N**, print **-1**.

#### Constraints

* **1 ≤ N, M ≤ 100000 = 105**
* **1 ≤ Xi, Yi ≤ N**
* There can be multiple edges connecting the same pair of vertices, There can be self loops too i.e. **Xi = Yi**

#### Example

```
Input:
7 7
1 2 
3 2
3 4
7 4
6 2
5 6
7 5

Output:
2
```

#### Explanation

We can consider two paths from **1** to **7**:

* **1-2-3-4-7**
* **1-2-6-5-7**

In the first one we need to revert edges **(3-2), (7-4)**. In the second one - **(6-2), (5-6), (7-5)**. So the answer is **min(2, 3) = 2**.

```java
class Codechef {
    static class Pair {
        int val, wt;

        Pair(int val, int wt) {
            this.val = val;
            this.wt = wt;
        }
    }

    // O(ElogV) -> Normal Dijkstra
    public static int findMinReverse(int[][] edges, int n) {
        List<Pair>[] graph = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int[] edge : edges) {
            graph[edge[0]].add(new Pair(edge[1], 0));
            graph[edge[1]].add(new Pair(edge[0], 1));
        }
        PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> a.wt - b.wt);
        boolean[] visited = new boolean[n];
        pq.add(new Pair(0, 0));
        while (pq.size() != 0) {
            Pair top = pq.poll();
            if (visited[top.val])
                continue;
            visited[top.val] = true;
            if (top.val == n - 1)
                return top.wt;
            for (Pair x : graph[top.val]) {
                // O(logn) operations
                pq.add(new Pair(x.val, x.wt + top.wt));
            }
        }
        return -1;
    }

    // O(E) -> 0 1 Dijksta (only works when only 2 wt edges are present)
    public static int findMinReverse(int[][] edges, int n) {
        List<Pair>[] graph = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int[] edge : edges) {
            graph[edge[0]].add(new Pair(edge[1], 0));
            graph[edge[1]].add(new Pair(edge[0], 1));
        }
        LinkedList<Pair> list = new LinkedList<>();
        boolean[] visited = new boolean[n];
        list.add(new Pair(0, 0));
        while (list.size() != 0) {
            Pair top = list.pollFirst();
            if (visited[top.val])
                continue;
            visited[top.val] = true;
            if (top.val == n - 1)
                return top.wt;
            for (Pair x : graph[top.val]) {
                // O(1) operations
                if (x.wt == 1)
                    list.addLast(new Pair(x.val, 1 + top.wt));
                else
                    list.addFirst(new Pair(x.val, top.wt));
            }
        }
        return -1;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://mayanktyagi3111.gitbook.io/interview-prep/graphs-bfs-and-dfs/chef-and-reversing.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.
