-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0133_clone_graph.html
More file actions
498 lines (430 loc) · 18.8 KB
/
0133_clone_graph.html
File metadata and controls
498 lines (430 loc) · 18.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
<!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><span class="keyword">def</span> <span class="function">cloneGraph</span>(self, node: <span class="class-name">Node</span>) -> Node:
<span class="keyword">if</span> <span class="keyword">not</span> node:
<span class="keyword">return</span> <span class="keyword">None</span>
clones = {} <span class="comment"># Map original -> clone</span>
<span class="keyword">def</span> <span class="function">dfs</span>(original: <span class="class-name">Node</span>) -> Node:
<span class="keyword">if</span> original <span class="keyword">in</span> clones:
<span class="keyword">return</span> clones[original]
<span class="comment"># Create clone</span>
clone = <span class="function">Node</span>(original.val)
clones[original] = clone
<span class="comment"># Clone neighbors</span>
<span class="keyword">for</span> neighbor <span class="keyword">in</span> original.neighbors:
clone.neighbors.<span class="function">append</span>(<span class="function">dfs</span>(neighbor))
<span class="keyword">return</span> clone
<span class="keyword">return</span> <span class="function">dfs</span>(node)</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>