You are given a directed graph with n nodes (labeled 0 to n - 1), represented as a list of directed edges edges where edges[i] = [u, v] indicates a directed edge from node u to node v. You are also given an integer array capacity of length n, where capacity[i] is the capacity value of node i.
Starting from a given source node, perform a graph traversal. You may only traverse an edge from node u to node v if capacity[u] is strictly greater than capacity[v].
Return a list of all nodes reachable from source (including the source itself), sorted in ascending order.
Function Signature
def reachable_nodes(n: int, edges: list[list[int]], capacity: list[int], source: int) -> list[int]:
Rules
-
An edge
[u, v]
can only be followed in its own direction, from
u
to
v
, and only when
capacity[u] > capacity[v]
. Equal capacities block the edge, and a self-loop
[u, u]
can never be used.
-
A node is reachable when some path from
source
uses only edges that pass this test.
source
is always reachable.
-
The same edge may appear more than once in
edges
; it behaves like a single edge.
-
Return each reachable node once, in ascending order.
Constraints
-
1 <= n <= 10^4
-
0 <= len(edges) <= 10^4
-
0 <= source < n
-
0 <= capacity[i] <= 10^6
-
len(capacity) == n
-
0 <= u, v < n
for each edge
[u, v]
Examples
Input: n = 6, edges = [[0,1],[0,2],[1,3],[2,4],[4,5]], capacity = [10,5,8,3,6,2], source = 0
Output: [0, 1, 2, 3, 4, 5]
From node 0 (capacity 10) we reach node 1 (5 < 10) and node 2 (8 < 10). From node 1 we reach node 3 (3 < 5), from node 2 we reach node 4 (6 < 8), and from node 4 we reach node 5 (2 < 6). All 6 nodes are reachable.
Input: n = 4, edges = [[0,1],[1,2],[2,3]], capacity = [5,5,3,1], source = 0
Output: [0]
The only edge out of node 0 leads to node 1, which also has capacity 5. Since 5 is not strictly greater than 5, the traversal stops at node 0, and nodes 2 and 3 stay unreachable even though their own edges would pass.
Input: n = 5, edges = [[0,1],[1,2],[0,3],[3,2],[2,4],[4,0]], capacity = [7,9,4,6,1], source = 0
Output: [0, 2, 3, 4]
The edge 0 to 1 is blocked (7 is not greater than 9), so node 1 is never reached. Node 2 is still reached through node 3 (7 > 6, then 6 > 4), and node 4 follows from node 2 (4 > 1). The edge from 4 back to 0 is blocked (1 is not greater than 7).