You are given a tree with n nodes labeled from 0 to n - 1, represented as a list of edges where each edges[i] = [u, v] indicates an undirected edge between nodes u and v.
A flood (or signal) starts from a given source node at time 0. At each unit of time, the flood spreads from every currently flooded node to all its directly connected neighbors that have not yet been flooded.
Return the total time it takes for the flood to reach all nodes in the tree.
Function Signature
def flood_time(n: int, edges: list[list[int]], source: int) -> int:
Rules
-
Edges are undirected: the flood can cross
[u, v]
from
u
to
v
or from
v
to
u
.
-
The source is flooded at time
0
. The answer is the time at which the last node becomes flooded, so a single-node tree returns
0
.
Constraints
-
1 <= n <= 10^5
-
len(edges) == n - 1
-
0 <= edges[i][0], edges[i][1] < n
-
0 <= source < n
-
The input represents a valid tree.
Examples
Input: n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], source = 0
Output: 2
Node 0 is the root of this tree. Nodes 1 and 2 flood at time 1, and nodes 3, 4 and 5 flood at time 2, so every node is flooded after 2 units of time.
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]], source = 0
Output: 4
The tree is a straight chain. The flood reaches node 1 at time 1, node 2 at time 2, node 3 at time 3 and node 4 at time 4.
Input: n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], source = 3
Output: 4
Same tree as the first example, flooded from a leaf. The farthest node from 3 is 5, along the path 3, 1, 0, 2, 5, which has 4 edges.