Minimum Direction Violations
GoogleMedium
You are given a directed graph with n nodes numbered 0 to n - 1 and a list of directed edges, where each edge [u, v] goes from u to v. You may traverse an edge in its own direction for free, or against its direction at a cost of 1. Edges may be traversed any number of times in either direction, and parallel edges and self loops may appear.
Part 1: Cheapest walk from start to end
Given the directed graph described above, return the smallest total cost of a walk from start to end, where traversing an edge against its direction costs 1 and traversing it in its direction costs 0.
Return -1 if no walk from start to end exists, even when edges may be walked backward. If start == end, the cost is 0.
- Example 1
- n
5- end
4- edges
[[0,1],[2,1],[2,3],[4,3]]- start
0- Output
2
Why: The walk 0, 1, 2, 3, 4 uses edge [0,1] forward, edge [2,1] backward, edge [2,3] forward and edge [4,3] backward, so two edges are walked against their direction.
Constraints
1 <= n <= 10^50 <= len(edges) <= 2 * 10^50 <= u < nand0 <= v < nfor every edge[u, v]0 <= start < n0 <= end < n