You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.
To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].
In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.
Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.
Input & Output
Example 1 — Basic Case
$Input:edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
›Output:13
💡 Note:From node 0: can reach node 2 (distance 2), then reach some nodes on edge [0,1] and [1,2]. Total reachable includes all original nodes and several subdivided nodes.
Example 2 — Simple Path
$Input:edges = [[0,1,4],[1,2,6]], maxMoves = 10, n = 3
›Output:23
💡 Note:Can traverse the entire path 0→1→2 and reach most subdivided nodes along the way within 10 moves.
Example 3 — No Subdivisions
$Input:edges = [[1,2,0],[2,3,0]], maxMoves = 3, n = 4
›Output:1
💡 Note:Starting from node 0, cannot reach any other nodes since node 0 is isolated. Only node 0 itself is reachable.
The key insight is to use Dijkstra's algorithm to find shortest paths to original nodes, then calculate how many subdivided nodes can be reached on each edge. Best approach is Dijkstra with Smart Edge Traversal. Time: O((V + E) log V), Space: O(V + E)
Common Approaches
✓
Brute Force BFS
⏱️ Time: O(E × M + V + E × M)
Space: O(E × M)
Create all subdivided nodes explicitly, then use BFS from node 0 to find all nodes within maxMoves distance. This approach constructs the complete graph with all intermediate nodes.
Dijkstra with Smart Edge Traversal
⏱️ Time: O((V + E) log V)
Space: O(V + E)
Apply Dijkstra's algorithm on the original graph to find shortest distances to all reachable nodes. For each edge, calculate how many subdivided nodes can be reached from both endpoints within the remaining moves.
Brute Force BFS — Algorithm Steps
Build complete subdivided graph with all intermediate nodes
Run BFS from node 0 with distance tracking
Count all nodes reachable within maxMoves
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Build Graph
Create all intermediate nodes explicitly
2
BFS Traversal
Visit nodes level by level from source
3
Count Reachable
Count all nodes within maxMoves distance
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODES 50000
#define MAX_NEIGHBORS 100
typedef struct {
int* items;
int front, rear, size;
} Queue;
typedef struct {
int** neighbors;
int* neighborCount;
int* capacity;
} Graph;
Queue* createQueue() {
Queue* q = malloc(sizeof(Queue));
q->items = malloc(MAX_NODES * 2 * sizeof(int));
q->front = q->rear = q->size = 0;
return q;
}
void enqueue(Queue* q, int node, int dist) {
q->items[q->rear * 2] = node;
q->items[q->rear * 2 + 1] = dist;
q->rear++;
q->size++;
}
void dequeue(Queue* q, int* node, int* dist) {
*node = q->items[q->front * 2];
*dist = q->items[q->front * 2 + 1];
q->front++;
q->size--;
}
Graph* createGraph() {
Graph* g = malloc(sizeof(Graph));
g->neighbors = malloc(MAX_NODES * sizeof(int*));
g->neighborCount = calloc(MAX_NODES, sizeof(int));
g->capacity = malloc(MAX_NODES * sizeof(int));
for (int i = 0; i < MAX_NODES; i++) {
g->neighbors[i] = malloc(MAX_NEIGHBORS * sizeof(int));
g->capacity[i] = MAX_NEIGHBORS;
}
return g;
}
void addEdge(Graph* g, int u, int v) {
if (g->neighborCount[u] >= g->capacity[u]) {
g->capacity[u] *= 2;
g->neighbors[u] = realloc(g->neighbors[u], g->capacity[u] * sizeof(int));
}
g->neighbors[u][g->neighborCount[u]++] = v;
}
void freeGraph(Graph* g) {
for (int i = 0; i < MAX_NODES; i++) {
free(g->neighbors[i]);
}
free(g->neighbors);
free(g->neighborCount);
free(g->capacity);
free(g);
}
int solution(int edges[][3], int edgeCount, int maxMoves, int n) {
Graph* graph = createGraph();
int* visited = calloc(MAX_NODES, sizeof(int));
int nodeId = n;
// Build subdivided graph
for (int i = 0; i < edgeCount; i++) {
int u = edges[i][0], v = edges[i][1], cnt = edges[i][2];
if (cnt == 0) {
addEdge(graph, u, v);
addEdge(graph, v, u);
} else {
// Create intermediate nodes
int prev = u;
for (int j = 0; j < cnt; j++) {
addEdge(graph, prev, nodeId);
addEdge(graph, nodeId, prev);
prev = nodeId;
nodeId++;
}
addEdge(graph, prev, v);
addEdge(graph, v, prev);
}
}
// BFS from node 0
Queue* queue = createQueue();
enqueue(queue, 0, 0);
visited[0] = 1;
int reachable = 1;
while (queue->size > 0) {
int node, dist;
dequeue(queue, &node, &dist);
for (int i = 0; i < graph->neighborCount[node]; i++) {
int neighbor = graph->neighbors[node][i];
if (!visited[neighbor] && dist + 1 <= maxMoves) {
visited[neighbor] = 1;
reachable++;
enqueue(queue, neighbor, dist + 1);
}
}
}
free(queue->items);
free(queue);
free(visited);
freeGraph(graph);
return reachable;
}
int main() {
char line[10000];
fgets(line, sizeof(line), stdin);
// Simple parsing for [[a,b,c],[d,e,f]] format
int edges[1000][3];
int edgeCount = 0;
char* ptr = strchr(line, '[');
ptr++; // Skip first [
while (*ptr && *ptr != ']') {
if (*ptr == '[') {
ptr++;
edges[edgeCount][0] = strtol(ptr, &ptr, 10);
ptr++; // Skip comma
edges[edgeCount][1] = strtol(ptr, &ptr, 10);
ptr++; // Skip comma
edges[edgeCount][2] = strtol(ptr, &ptr, 10);
edgeCount++;
}
ptr++;
}
int maxMoves, n;
scanf("%d", &maxMoves);
scanf("%d", &n);
printf("%d\n", solution(edges, edgeCount, maxMoves, n));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(E × M + V + E × M)
Building subdivided graph takes O(E × M) where E is edges and M is average subdivision count, BFS takes O(V + E × M)
n
2n
✓ Linear Growth
Space Complexity
O(E × M)
Storing all subdivided nodes and edges requires O(E × M) space
n
2n
✓ Linear Space
28.5K Views
MediumFrequency
~35 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.