Problem · Graph
Minimum Direction Violations
Learn this problemProblem statement
You are given a directed graph with n vertices numbered from 0 to n - 1. Each pair [u, v] in edges is an original directed edge from u to v.
You may traverse every listed edge in either direction:
- Traversing from
utov, the original direction, costs0violations. - Traversing from
vtou, against the original direction, costs1violation.
Return the minimum total number of direction violations needed to travel from start to end.
Function
minimumDirectionViolations(n: int, edges: int[][], start: int, end: int) → intExamples
Example 1
n = 5edges = [[0,1],[2,1],[2,3],[4,3]]start = 0end = 4return = 2Follow 0 -> 1, reverse 2 -> 1 to move 1 -> 2, follow 2 -> 3, and reverse 4 -> 3 to move 3 -> 4. Exactly two traversals oppose their original directions, and no path uses fewer violations.
Example 2
n = 4edges = [[0,1],[1,2],[2,3]]start = 0end = 3return = 0The path 0 -> 1 -> 2 -> 3 follows every original edge direction, so its total violation cost is 0.
Example 3
n = 3edges = [[1,0],[0,2],[2,1]]start = 0end = 1return = 0Reversing the direct edge 1 -> 0 would cost 1, but the longer path 0 -> 2 -> 1 follows original directions and costs 0.
Constraints
1 <= n <= 1000000 <= edges.length <= 200000- Every entry in
edgescontains exactly two valid vertex indices. 0 <= start, end < nendis reachable fromstartwhen all edge directions are ignored.