-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0133_clone_graph.html
More file actions
675 lines (565 loc) · 23.8 KB
/
0133_clone_graph.html
File metadata and controls
675 lines (565 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clone Graph - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
</div>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#0133</span> Clone Graph</h1>
<p>
Given a reference of a node in a connected undirected graph, return a <strong>deep copy (clone)</strong> of the graph.
Each node contains a value and a list of its neighbors.
</p>
<p><strong>Example:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]] → Clone with same structure</p>
<p><strong>Approach:</strong> DFS/BFS with hashmap to track original → clone mapping</p>
<p><strong>Time Complexity:</strong> O(V + E) | <strong>Space Complexity:</strong> O(V)</p>
<div class="problem-meta">
<span class="meta-tag">🔗 Graph</span>
<span class="meta-tag">⏱️ O(m×n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0133_clone_graph/0133_clone_graph.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Graph problems are like <strong>exploring a maze</strong>:</p>
<ul>
<li><strong>Nodes:</strong> Points or locations</li>
<li><strong>Edges:</strong> Connections between nodes</li>
<li><strong>Traverse:</strong> Use DFS or BFS to explore</li>
<li><strong>Track visited:</strong> Avoid infinite loops</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn" class="btn">Step</button>
<button id="autoBtn" class="btn">Auto Run</button>
<button id="resetBtn" class="btn btn-secondary">Reset</button>
<div class="speed-control">
<label for="speedSlider">Speed:</label>
<input type="range" id="speedSlider" min="1" max="10" value="5">
</div>
</div>
<svg id="visualization" width="900" height="500"></svg>
<div class="variables-display">
<div id="varDisplay"></div>
</div>
<div class="status-message" id="statusMessage">Press "Step" or "Auto Run" to begin</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Optional
from collections import deque
"""
LeetCode Clone Graph
Problem from LeetCode: https://leetcode.com/problems/clone-graph/
Description:
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Example 2:
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
class Solution:
def cloneGraph(self, node: Optional[Node]) -> Optional[Node]:
"""
Deep clone a graph using DFS.
Args:
node: Reference to a node in the graph
Returns:
Node: Reference to the corresponding node in the cloned graph
"""
if not node:
return None
# Dictionary to map original nodes to their clones
clones = {}
def dfs(original: Node) -> Node:
# If node is already cloned, return its clone
if original in clones:
return clones[original]
# Create a clone of the current node
clone = Node(original.val)
# Map the original node to its clone
clones[original] = clone
# Clone all neighbors and connect them to the current clone
for neighbor in original.neighbors:
clone.neighbors.append(dfs(neighbor))
return clone
return dfs(node)
def cloneGraph_bfs(self, node: Optional[Node]) -> Optional[Node]:
"""
Deep clone a graph using BFS.
Args:
node: Reference to a node in the graph
Returns:
Node: Reference to the corresponding node in the cloned graph
"""
if not node:
return None
# Dictionary to map original nodes to their clones
clones = {}
# Create a clone of the starting node
clones[node] = Node(node.val)
# Initialize queue with the starting node
queue = deque([node])
while queue:
original = queue.popleft()
# Process each neighbor of the original node
for neighbor in original.neighbors:
if neighbor not in clones:
# Create clone for this neighbor if not already cloned
clones[neighbor] = Node(neighbor.val)
# Add neighbor to queue for further processing
queue.append(neighbor)
# Connect the clone of the current node to the clone of the neighbor
clones[original].neighbors.append(clones[neighbor])
return clones[node]
# Helper function to create a graph from an adjacency list
def create_graph_from_adj_list(adj_list):
if not adj_list:
return None
# Create nodes
nodes = [Node(i+1) for i in range(len(adj_list))]
# Connect neighbors
for i, neighbors in enumerate(adj_list):
for neighbor in neighbors:
nodes[i].neighbors.append(nodes[neighbor-1])
return nodes[0] if nodes else None
# Helper function to convert a graph to an adjacency list
def graph_to_adj_list(node):
if not node:
return []
visited = {}
result = []
def dfs(n):
if n.val in visited:
return
# Mark as visited
visited[n.val] = True
# Ensure result list is long enough
while len(result) < n.val:
result.append([])
# Add neighbors to adjacency list
for neighbor in n.neighbors:
result[n.val-1].append(neighbor.val)
dfs(neighbor)
dfs(node)
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
adj_list1 = [[2, 4], [1, 3], [2, 4], [1, 3]]
graph1 = create_graph_from_adj_list(adj_list1)
cloned1 = solution.cloneGraph(graph1)
result1 = graph_to_adj_list(cloned1)
print(f"Example 1: {result1}") # Expected: [[2, 4], [1, 3], [2, 4], [1, 3]]
# Example 2
adj_list2 = [[]]
graph2 = create_graph_from_adj_list(adj_list2)
cloned2 = solution.cloneGraph(graph2)
result2 = graph_to_adj_list(cloned2)
print(f"Example 2: {result2}") # Expected: [[]]
# Example 3
adj_list3 = []
graph3 = create_graph_from_adj_list(adj_list3)
cloned3 = solution.cloneGraph(graph3)
result3 = graph_to_adj_list(cloned3)
print(f"Example 3: {result3}") # Expected: []
# Compare with BFS approach
cloned4 = solution.cloneGraph_bfs(graph1)
result4 = graph_to_adj_list(cloned4)
print(f"\nBFS approach for Example 1: {result4}")
</pre>
</div>
</div>
</div>
<script>
// Graph: [[2,4],[1,3],[2,4],[1,3]] - Square graph
// Node 1 connects to 2, 4
// Node 2 connects to 1, 3
// Node 3 connects to 2, 4
// Node 4 connects to 1, 3
const originalPositions = {
1: { x: 120, y: 120 },
2: { x: 280, y: 120 },
3: { x: 280, y: 280 },
4: { x: 120, y: 280 }
};
const clonePositions = {
1: { x: 520, y: 120 },
2: { x: 680, y: 120 },
3: { x: 680, y: 280 },
4: { x: 520, y: 280 }
};
const edges = [[1, 2], [2, 3], [3, 4], [4, 1]];
// State
let step = 0;
let autoRunning = false;
let autoInterval = null;
// Generate steps
const steps = [];
function generateSteps() {
steps.length = 0;
steps.push({
type: 'init',
cloned: [],
processing: null,
cloneMap: {},
message: 'Original graph with 4 nodes. Clone using DFS + hashmap.'
});
steps.push({
type: 'start',
cloned: [],
processing: 1,
cloneMap: {},
message: 'Start DFS from node 1. Create clone of node 1.'
});
steps.push({
type: 'clone',
cloned: [1],
processing: 1,
cloneMap: { 1: "1'" },
message: 'Clone node 1 created. Add to hashmap: {1 → 1\'}. Visit neighbors.'
});
steps.push({
type: 'visit_neighbor',
cloned: [1],
processing: 2,
cloneMap: { 1: "1'" },
parent: 1,
message: 'Visit neighbor 2 of node 1. Node 2 not cloned yet.'
});
steps.push({
type: 'clone',
cloned: [1, 2],
processing: 2,
cloneMap: { 1: "1'", 2: "2'" },
message: 'Clone node 2 created. Add to hashmap. Visit neighbors of 2.'
});
steps.push({
type: 'visit_neighbor',
cloned: [1, 2],
processing: 1,
cloneMap: { 1: "1'", 2: "2'" },
parent: 2,
alreadyCloned: true,
message: 'Neighbor 1 of node 2 already cloned. Return existing clone.'
});
steps.push({
type: 'visit_neighbor',
cloned: [1, 2],
processing: 3,
cloneMap: { 1: "1'", 2: "2'" },
parent: 2,
message: 'Visit neighbor 3 of node 2. Node 3 not cloned yet.'
});
steps.push({
type: 'clone',
cloned: [1, 2, 3],
processing: 3,
cloneMap: { 1: "1'", 2: "2'", 3: "3'" },
message: 'Clone node 3 created. Add to hashmap. Visit neighbors of 3.'
});
steps.push({
type: 'visit_neighbor',
cloned: [1, 2, 3],
processing: 2,
cloneMap: { 1: "1'", 2: "2'", 3: "3'" },
parent: 3,
alreadyCloned: true,
message: 'Neighbor 2 of node 3 already cloned. Return existing clone.'
});
steps.push({
type: 'visit_neighbor',
cloned: [1, 2, 3],
processing: 4,
cloneMap: { 1: "1'", 2: "2'", 3: "3'" },
parent: 3,
message: 'Visit neighbor 4 of node 3. Node 4 not cloned yet.'
});
steps.push({
type: 'clone',
cloned: [1, 2, 3, 4],
processing: 4,
cloneMap: { 1: "1'", 2: "2'", 3: "3'", 4: "4'" },
message: 'Clone node 4 created. All nodes cloned!'
});
steps.push({
type: 'connect',
cloned: [1, 2, 3, 4],
processing: null,
cloneMap: { 1: "1'", 2: "2'", 3: "3'", 4: "4'" },
connecting: true,
message: 'Connect all cloned nodes according to original edges.'
});
steps.push({
type: 'done',
cloned: [1, 2, 3, 4],
processing: null,
cloneMap: { 1: "1'", 2: "2'", 3: "3'", 4: "4'" },
complete: true,
message: 'Done! Graph cloned successfully. Both graphs are independent copies.'
});
}
// SVG setup
const svg = d3.select("#visualization");
const width = 900;
const height = 500;
function draw(currentStep) {
svg.selectAll("*").remove();
const data = currentStep || steps[0];
// Draw arrow marker
svg.append("defs").append("marker")
.attr("id", "arrow")
.attr("viewBox", "0 0 10 10")
.attr("refX", 5)
.attr("refY", 5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z")
.attr("fill", "#f59e0b");
// Labels
svg.append("text")
.attr("x", 200)
.attr("y", 40)
.attr("text-anchor", "middle")
.attr("class", "label")
.text("Original Graph");
svg.append("text")
.attr("x", 600)
.attr("y", 40)
.attr("text-anchor", "middle")
.attr("class", "label")
.text("Cloned Graph");
// Draw original graph edges
edges.forEach(([from, to]) => {
const x1 = originalPositions[from].x;
const y1 = originalPositions[from].y;
const x2 = originalPositions[to].x;
const y2 = originalPositions[to].y;
svg.append("line")
.attr("x1", x1)
.attr("y1", y1)
.attr("x2", x2)
.attr("y2", y2)
.attr("stroke", "#667eea")
.attr("stroke-width", 2);
});
// Draw original graph nodes
[1, 2, 3, 4].forEach(val => {
const pos = originalPositions[val];
let fill = "#667eea";
let stroke = "none";
let strokeWidth = 0;
if (data.processing === val && !data.alreadyCloned) {
fill = "#f59e0b";
stroke = "#d97706";
strokeWidth = 3;
} else if (data.cloned && data.cloned.includes(val)) {
fill = "#4ade80";
}
svg.append("circle")
.attr("cx", pos.x)
.attr("cy", pos.y)
.attr("r", 28)
.attr("fill", fill)
.attr("stroke", stroke)
.attr("stroke-width", strokeWidth);
svg.append("text")
.attr("x", pos.x)
.attr("y", pos.y + 6)
.attr("text-anchor", "middle")
.attr("fill", "white")
.attr("font-weight", "bold")
.attr("font-size", "18px")
.text(val);
});
// Draw clone edges
if (data.connecting || data.complete) {
edges.forEach(([from, to]) => {
const x1 = clonePositions[from].x;
const y1 = clonePositions[from].y;
const x2 = clonePositions[to].x;
const y2 = clonePositions[to].y;
svg.append("line")
.attr("x1", x1)
.attr("y1", y1)
.attr("x2", x2)
.attr("y2", y2)
.attr("stroke", "#4ade80")
.attr("stroke-width", 2);
});
}
// Draw cloned nodes
if (data.cloned && data.cloned.length > 0) {
data.cloned.forEach(val => {
const pos = clonePositions[val];
const isNew = data.processing === val && data.type === 'clone';
svg.append("circle")
.attr("cx", pos.x)
.attr("cy", pos.y)
.attr("r", 28)
.attr("fill", "#4ade80")
.attr("stroke", isNew ? "#16a34a" : "none")
.attr("stroke-width", isNew ? 4 : 0);
svg.append("text")
.attr("x", pos.x)
.attr("y", pos.y + 6)
.attr("text-anchor", "middle")
.attr("fill", "white")
.attr("font-weight", "bold")
.attr("font-size", "16px")
.text(val + "'");
});
}
// Draw mapping arrows
if (data.cloned && data.cloned.length > 0 && data.type !== 'init') {
data.cloned.forEach(val => {
const orig = originalPositions[val];
const clone = clonePositions[val];
svg.append("path")
.attr("d", `M ${orig.x + 35} ${orig.y} Q ${(orig.x + clone.x) / 2} ${orig.y - 30} ${clone.x - 35} ${clone.y}`)
.attr("fill", "none")
.attr("stroke", "#f59e0b")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5,5")
.attr("marker-end", "url(#arrow)");
});
}
// Draw hashmap
svg.append("text")
.attr("x", 400)
.attr("y", 380)
.attr("text-anchor", "middle")
.attr("class", "label")
.text("Clone Map (HashMap):");
if (data.cloneMap && Object.keys(data.cloneMap).length > 0) {
const entries = Object.entries(data.cloneMap);
entries.forEach(([key, value], i) => {
const x = 280 + i * 70;
svg.append("rect")
.attr("x", x)
.attr("y", 395)
.attr("width", 60)
.attr("height", 30)
.attr("rx", 6)
.attr("fill", "#fef3c7")
.attr("stroke", "#f59e0b");
svg.append("text")
.attr("x", x + 30)
.attr("y", 415)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.text(`${key}→${value}`);
});
} else {
svg.append("text")
.attr("x", 400)
.attr("y", 415)
.attr("text-anchor", "middle")
.attr("fill", "#9ca3af")
.text("{ }");
}
// Legend
const legendY = 460;
svg.append("circle").attr("cx", 150).attr("cy", legendY).attr("r", 10).attr("fill", "#667eea");
svg.append("text").attr("x", 165).attr("y", legendY + 4).attr("fill", "#4b5563").text("Original");
svg.append("circle").attr("cx", 280).attr("cy", legendY).attr("r", 10).attr("fill", "#f59e0b");
svg.append("text").attr("x", 295).attr("y", legendY + 4).attr("fill", "#4b5563").text("Processing");
svg.append("circle").attr("cx", 420).attr("cy", legendY).attr("r", 10).attr("fill", "#4ade80");
svg.append("text").attr("x", 435).attr("y", legendY + 4).attr("fill", "#4b5563").text("Cloned");
// Update status
document.getElementById("statusMessage").textContent = data.message;
// Update variables
document.getElementById("varDisplay").innerHTML = `
<span class="var-item">Processing: ${data.processing || 'None'}</span>
<span class="var-item">Cloned: [${data.cloned ? data.cloned.join(', ') : ''}]</span>
<span class="var-item">Map Size: ${data.cloneMap ? Object.keys(data.cloneMap).length : 0}</span>
`;
}
function doStep() {
if (step >= steps.length) {
stopAuto();
return;
}
draw(steps[step]);
step++;
}
function stopAuto() {
autoRunning = false;
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById("autoBtn").textContent = "Auto Run";
}
function toggleAuto() {
if (autoRunning) {
stopAuto();
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 11 - document.getElementById("speedSlider").value;
autoInterval = setInterval(() => {
if (step >= steps.length) {
stopAuto();
return;
}
doStep();
}, speed * 200);
}
}
function reset() {
stopAuto();
step = 0;
draw(steps[0]);
}
// Initialize
generateSteps();
draw(steps[0]);
// Event listeners
document.getElementById("stepBtn").addEventListener("click", doStep);
document.getElementById("autoBtn").addEventListener("click", toggleAuto);
document.getElementById("resetBtn").addEventListener("click", reset);
</script>
</body>
</html>