Problem 533793 · medium · Phase 05 Advanced Algorithms & Graphs

Nodes Within K Hops

graphs · BFS · levels

An undirected graph with nodes 0 .. n-1 is given as n and an edge list edges (edges[i] = [u, v]). The hop distance between two nodes is the smallest number of edges on a path between them. Return how many nodes (including source itself) have hop distance at most k from source.

Examples

Input:  n = 6, edges = [[0,1],[1,2],[2,3],[3,4],[0,5]], source = 0, k = 2
Output: 4
Explanation: distance 0: {0}; distance 1: {1, 5}; distance 2: {2}. Node 3 is 3 hops away.

Input:  n = 4, edges = [[0,1],[1,2],[2,0]], source = 3, k = 5
Output: 1
Explanation: node 3 is isolated.

Constraints

  • 1 <= n <= 2 * 10**4, 0 <= k <= n
  • Edges may be repeated; no self-loops.
  • Target O(V + E) time.

Goals

  • Track BFS distance (level) per node
  • Stop expanding once the level limit is reached
Starting Python…