#882

Reachable Nodes In Subdivided Graph

Hard
Graph TheoryHeap (Priority Queue)Shortest PathGraph TraversalPriority QueueDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(E log V)
Space
O(1)
O(V)
💡

Intuition

Time O(E log V)Space O(V)

The optimal solution uses a priority queue (min-heap) to efficiently explore the graph, prioritizing nodes based on the distance traveled. This allows us to explore the most promising paths first and ensures we stay within the maxMoves limit while counting reachable nodes.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph representation using an adjacency list.
  2. 2Step 2: Use a min-heap to explore nodes starting from node 0, keeping track of the distance traveled.
  3. 3Step 3: For each node, calculate the maximum number of new nodes that can be reached from its edges and update the reachable count accordingly.
solution.py26 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def reachableNodes(edges, maxMoves, n):
6    graph = defaultdict(list)
7    for u, v, cnt in edges:
8        graph[u].append((v, cnt))
9        graph[v].append((u, cnt))
10
11    heap = [(0, 0)]  # (distance, node)
12    reachable = 0
13    visited = set()
14    while heap:
15        dist, node = heapq.heappop(heap)
16        if node in visited:
17            continue
18        visited.add(node)
19        reachable += 1
20        for neighbor, cnt in graph[node]:
21            if neighbor not in visited:
22                new_dist = dist + cnt + 1
23                if new_dist <= maxMoves:
24                    heapq.heappush(heap, (new_dist, neighbor))
25
26    return reachable

Complexity note: The complexity is O(E log V) due to the priority queue operations, where E is the number of edges and V is the number of vertices.

  • 1Understanding graph traversal is crucial.
  • 2Using a priority queue can optimize the search process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.