Problem · Graph
Distances to the Nearest Infected Node
Learn this problemProblem statement
You are given an undirected, unweighted graph with n nodes numbered from 0 to n - 1. The array infected contains the distinct nodes that are already infected.
Return an integer array distance of length n, where distance[v] is the minimum number of edges on a path from node v to any infected node. Return -1 for a node that cannot reach any infected node.
Function
nearestInfectedDistances(n: int, edges: int[][], infected: int[]) → int[]Examples
Example 1
n = 7edges = [[0,1],[1,2],[2,3],[4,5]]infected = [0,3,5]return = [0,1,1,0,1,0,-1]Nodes 0, 3, and 5 start at distance 0. Nodes 1, 2, and 4 are one edge from an infected node. Node 6 is isolated, so its distance is -1.
Example 2
n = 5edges = [[0,1],[1,2],[2,3],[3,4]]infected = [1,4]return = [1,0,1,1,0]A shortest path may end at either infected source. Node 3, for example, is one edge from node 4.
Constraints
1 <= n <= 2000000 <= edges.length <= 200000- Every row of
edgesis[u, v]with0 <= u, v < nandu != v. 1 <= infected.length <= n- All entries of
infectedare distinct valid node indices.