-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0261_graph_valid_tree.html
More file actions
509 lines (438 loc) · 20.6 KB
/
0261_graph_valid_tree.html
File metadata and controls
509 lines (438 loc) · 20.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>261 - Graph Valid Tree</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.grid-container { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
.legend { display: flex; justify-content: center; gap: 20px; margin: 15px 0; flex-wrap: wrap; }
.legend-item { display: flex; align-items: center; gap: 8px; font-size: 0.85rem; color: #64748b; }
.legend-color { width: 20px; height: 20px; border-radius: 50%; }
#graphArea { min-height: 350px; }
.result { font-size: 1.3rem; text-align: center; padding: 15px; border-radius: 8px; margin-top: 15px; }
.result.valid { background: rgba(34, 197, 94, 0.2); border: 2px solid #22c55e; color: #166534; }
.result.invalid { background: rgba(239, 68, 68, 0.2); border: 2px solid #ef4444; color: #dc2626; }
.uf-visual { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; margin-top: 15px; }
.uf-set { background: #f1f5f9; border: 1px solid #6366f1; border-radius: 8px; padding: 10px; min-width: 60px; text-align: center; color: #334155; }
.uf-set.merged { background: rgba(34, 197, 94, 0.2); border-color: #22c55e; }
select { background: #f8fafc; color: #334155; border: 1px solid #e2e8f0; padding: 10px; border-radius: 8px; }
select:focus { outline: none; border-color: #6366f1; }
.info-box { background: #f1f5f9; border-radius: 8px; padding: 15px; margin-bottom: 15px; font-size: 0.9rem; line-height: 1.6; color: #475569; }
</style>
</head>
<body>
<div class="container">
<section class="problem-info">
<h1><span class="problem-number">#261</span> Graph Valid Tree</h1>
<p>Given n nodes and a list of undirected edges, check if these edges form a valid tree. A valid tree must have exactly n-1 edges, be fully connected, and have no cycles.</p>
<div class="problem-meta">
<span class="meta-tag">Medium</span>
<span class="meta-tag">Graph</span>
<span class="meta-tag">Union Find</span>
<span class="meta-tag">DFS/BFS</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0261_graph_valid_tree/0261_graph_valid_tree.py</code>
</div>
</section>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>A stack works like a <strong>pile of plates</strong> - last in, first out (LIFO):</p>
<ul>
<li><strong>Push:</strong> Add item to the top</li>
<li><strong>Pop:</strong> Remove and return the top item</li>
<li><strong>Peek:</strong> Look at top without removing</li>
<li><strong>Match pairs:</strong> Great for matching brackets, parentheses</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<select id="exampleSelect" onchange="loadExample()">
<option value="valid">Valid Tree (5 nodes)</option>
<option value="invalid-cycle">Invalid: Has Cycle</option>
<option value="invalid-disconnected">Invalid: Disconnected</option>
</select>
<button id="stepBtn" onclick="step()">Step</button>
<button id="autoBtn" onclick="toggleAuto()">▶ Auto Run</button>
<button onclick="reset()">Reset</button>
</div>
</section>
<div class="grid-container">
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="info-box">
A valid tree must: 1) Have exactly n-1 edges, 2) Be fully connected, 3) Have no cycles.
Using Union-Find: if adding edge creates cycle (same parent), not a tree.
</div>
<svg id="graphArea" width="100%" height="350"></svg>
</section>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="legend">
<div class="legend-item"><div class="legend-color" style="background: #6366f1;"></div> Unvisited</div>
<div class="legend-item"><div class="legend-color" style="background: #f59e0b;"></div> Processing</div>
<div class="legend-item"><div class="legend-color" style="background: #22c55e;"></div> Connected</div>
<div class="legend-item"><div class="legend-color" style="background: #ef4444;"></div> Cycle Found</div>
</div>
<div id="ufVisual" class="uf-visual"></div>
<div id="edgeList" style="margin-top: 15px;"></div>
</section>
</div>
<section class="visualization-section">
<div class="status-message" id="stepDisplay">Ready to start</div>
<div id="resultArea"></div>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
from collections import defaultdict, deque
"""
LeetCode 261. Graph Valid Tree
Problem from LeetCode: https://leetcode.com/problems/graph-valid-tree/
Description:
You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph.
Return true if the edges of the given graph make up a valid tree, and false otherwise.
A graph is a valid tree if:
- It is connected (there is a path between every pair of nodes).
- It has n - 1 edges.
- It has no cycles.
Example 1:
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Explanation: The graph is a valid tree with 5 nodes and 4 edges.
Example 2:
Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Explanation: The graph has a cycle: 1-2-3-1.
Constraints:
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
- edges[i].length == 2
- 0 <= ai, bi < n
- ai != bi
- There are no self-loops or repeated edges.
"""
class Solution:
def valid_tree(self, n: int, edges: List[List[int]]) ->bool:
"""
Determine if the given edges form a valid tree.
For a graph to be a valid tree:
1. It must be fully connected (one component)
2. It must have no cycles (edges = nodes - 1)
Args:
n: Number of nodes (labeled from 0 to n-1)
edges: List of undirected edges
Returns:
bool: True if the given edges form a valid tree, False otherwise
"""
# Quick check: a tree with n nodes must have exactly n-1 edges
if len(edges) != n - 1:
return False
# Build adjacency list
adj_list = defaultdict(list)
for src, dest in edges:
adj_list[src].append(dest)
adj_list[dest].append(src)
# DFS to check if all nodes are connected
stack = [0]
visited = {0}
while stack:
node = stack.pop()
for neighbor in adj_list[node]:
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
# If all nodes are connected, the graph is a valid tree
return len(visited) == n
def valid_tree_b_f_s(self, n: int, edges: List[List[int]]) ->bool:
"""
Determine if the given edges form a valid tree using BFS.
Args:
n: Number of nodes (labeled from 0 to n-1)
edges: List of undirected edges
Returns:
bool: True if the given edges form a valid tree, False otherwise
"""
# Quick check: a tree with n nodes must have exactly n-1 edges
if len(edges) != n - 1:
return False
# Build adjacency list
adj_list = defaultdict(list)
for src, dest in edges:
adj_list[src].append(dest)
adj_list[dest].append(src)
# BFS to check if all nodes are connected
queue = deque([0])
visited = {0}
while queue:
node = queue.popleft()
for neighbor in adj_list[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# If all nodes are connected, the graph is a valid tree
return len(visited) == n
def valid_tree_union_find(self, n: int, edges: List[List[int]]) ->bool:
"""
Determine if the given edges form a valid tree using Union-Find.
Args:
n: Number of nodes (labeled from 0 to n-1)
edges: List of undirected edges
Returns:
bool: True if the given edges form a valid tree, False otherwise
"""
# Quick check: a tree with n nodes must have exactly n-1 edges
if len(edges) != n - 1:
return False
# Initialize parent array for union-find
parent = list(range(n))
# Find function with path compression
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
# Union function
def union(x, y):
parent[find(x)] = find(y)
# Process each edge
for x, y in edges:
# If nodes are already in the same set, adding this edge creates a cycle
if find(x) == find(y):
return False
union(x, y)
return True
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
n1 = 5
edges1 = [[0,1],[0,2],[0,3],[1,4]]
result1 = solution.valid_tree(n1, edges1)
print(f"Example 1: n = {n1}, edges = {edges1}")
print(f"Output (DFS): {result1}") # Expected output: True
# Example 2
n2 = 5
edges2 = [[0,1],[1,2],[2,3],[1,3],[1,4]]
result2 = solution.valid_tree(n2, edges2)
print(f"\nExample 2: n = {n2}, edges = {edges2}")
print(f"Output (DFS): {result2}") # Expected output: False
# Using BFS approach
print("\nUsing BFS approach:")
print(f"Example 1: {solution.valid_tree_b_f_s(n1, edges1)}") # Expected output: True
print(f"Example 2: {solution.valid_tree_b_f_s(n2, edges2)}") # Expected output: False
# Using Union-Find approach
print("\nUsing Union-Find approach:")
print(f"Example 1: {solution.valid_tree_union_find(n1, edges1)}") # Expected output: True
print(f"Example 2: {solution.valid_tree_union_find(n2, edges2)}") # Expected output: False
</pre>
</div>
</section>
</div>
<script>
const examples = {
'valid': {
n: 5,
edges: [[0, 1], [0, 2], [0, 3], [1, 4]],
positions: [{x: 200, y: 50}, {x: 100, y: 150}, {x: 200, y: 150}, {x: 300, y: 150}, {x: 100, y: 250}]
},
'invalid-cycle': {
n: 5,
edges: [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]],
positions: [{x: 200, y: 50}, {x: 200, y: 150}, {x: 100, y: 250}, {x: 300, y: 250}, {x: 200, y: 250}]
},
'invalid-disconnected': {
n: 5,
edges: [[0, 1], [2, 3]],
positions: [{x: 100, y: 100}, {x: 100, y: 200}, {x: 300, y: 100}, {x: 300, y: 200}, {x: 200, y: 300}]
}
};
let currentExample = 'valid';
let n = 5;
let edges = [];
let positions = [];
let parent = [];
let rank = [];
let steps = [];
let stepIndex = 0;
let autoInterval = null;
function loadExample() {
currentExample = document.getElementById('exampleSelect').value;
reset();
}
function find(x) {
if (parent[x] !== x) parent[x] = find(parent[x]);
return parent[x];
}
function reset() {
const ex = examples[currentExample];
n = ex.n;
edges = [...ex.edges];
positions = [...ex.positions];
parent = Array.from({length: n}, (_, i) => i);
rank = Array(n).fill(0);
steps = [];
stepIndex = 0;
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = '▶ Auto Run';
}
if (edges.length !== n - 1) {
steps.push({
type: 'edge-count',
valid: false,
desc: `Edge count ${edges.length} ≠ n-1 (${n-1}). Not a valid tree!`
});
} else {
const tempParent = Array.from({length: n}, (_, i) => i);
for (let i = 0; i < edges.length; i++) {
const [a, b] = edges[i];
let pa = a, pb = b;
while (tempParent[pa] !== pa) pa = tempParent[pa];
while (tempParent[pb] !== pb) pb = tempParent[pb];
if (pa === pb) {
steps.push({
type: 'cycle',
edgeIdx: i,
a, b, pa, pb,
parent: [...tempParent],
desc: `Edge [${a}, ${b}]: Both have same root ${pa}. CYCLE DETECTED!`
});
break;
} else {
tempParent[pa] = pb;
steps.push({
type: 'union',
edgeIdx: i,
a, b, pa, pb,
parent: [...tempParent],
desc: `Edge [${a}, ${b}]: Union roots ${pa} → ${pb}. Connected!`
});
}
}
if (steps.length === edges.length && steps[steps.length - 1].type !== 'cycle') {
steps.push({
type: 'complete',
valid: true,
parent: [...steps[steps.length - 1].parent],
desc: `All ${edges.length} edges processed. Valid tree!`
});
}
}
render();
}
function step() {
if (stepIndex >= steps.length) return;
const s = steps[stepIndex];
if (s.parent) parent = [...s.parent];
stepIndex++;
render();
}
function toggleAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = '▶ Auto Run';
} else {
autoInterval = setInterval(() => {
if (stepIndex >= steps.length) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = '▶ Auto Run';
} else {
step();
}
}, 1000);
document.getElementById('autoBtn').textContent = '⏸ Pause';
}
}
function render() {
const svg = d3.select('#graphArea');
svg.selectAll('*').remove();
const width = svg.node().getBoundingClientRect().width;
const height = 350;
const g = svg.append('g').attr('transform', 'translate(50, 20)');
const curStep = stepIndex > 0 ? steps[stepIndex - 1] : null;
const processedEdges = curStep?.edgeIdx !== undefined ? curStep.edgeIdx + 1 : 0;
edges.forEach(([a, b], i) => {
let strokeColor = '#94a3b8';
let strokeWidth = 3;
if (curStep) {
if (i < processedEdges - 1 || (i === processedEdges - 1 && curStep.type !== 'cycle')) {
strokeColor = '#22c55e';
} else if (i === processedEdges - 1 && curStep.type === 'cycle') {
strokeColor = '#ef4444';
strokeWidth = 5;
} else if (i === processedEdges - 1) {
strokeColor = '#f59e0b';
strokeWidth = 4;
}
}
g.append('line')
.attr('x1', positions[a].x).attr('y1', positions[a].y)
.attr('x2', positions[b].x).attr('y2', positions[b].y)
.attr('stroke', strokeColor).attr('stroke-width', strokeWidth);
});
for (let i = 0; i < n; i++) {
let fillColor = '#6366f1';
if (curStep && curStep.type !== 'edge-count') {
if (curStep.a === i || curStep.b === i) {
fillColor = curStep.type === 'cycle' ? '#ef4444' : '#f59e0b';
} else if (parent[i] !== i || i === find(0)) {
fillColor = '#22c55e';
}
}
g.append('circle')
.attr('cx', positions[i].x).attr('cy', positions[i].y).attr('r', 25)
.attr('fill', fillColor).attr('stroke', '#fff').attr('stroke-width', 2);
g.append('text')
.attr('x', positions[i].x).attr('y', positions[i].y + 5)
.attr('text-anchor', 'middle').attr('fill', '#fff').attr('font-weight', 'bold')
.text(i);
}
let ufHtml = '<div style="font-size: 0.9rem; margin-bottom: 10px; color: #64748b;">Parent array:</div>';
ufHtml += '<div style="display: flex; gap: 5px; justify-content: center;">';
for (let i = 0; i < n; i++) {
const isMerged = parent[i] !== i;
ufHtml += `<div class="uf-set ${isMerged ? 'merged' : ''}">
<div style="font-size: 0.7rem; color: #94a3b8;">${i}</div>
<div style="font-weight: bold;">${parent[i]}</div>
</div>`;
}
ufHtml += '</div>';
document.getElementById('ufVisual').innerHTML = ufHtml;
let edgeHtml = '<div style="font-size: 0.9rem; margin-bottom: 10px; color: #64748b;">Edges to process:</div>';
edges.forEach(([a, b], i) => {
let style = 'padding: 5px 10px; margin: 3px; border-radius: 5px; display: inline-block; ';
if (i < processedEdges) {
if (curStep && i === processedEdges - 1 && curStep.type === 'cycle') {
style += 'background: rgba(239,68,68,0.3); border: 1px solid #ef4444; color: #dc2626;';
} else {
style += 'background: rgba(34,197,94,0.3); border: 1px solid #22c55e; color: #166534;';
}
} else {
style += 'background: #f1f5f9; border: 1px solid #e2e8f0; color: #64748b;';
}
edgeHtml += `<span style="${style}">[${a}, ${b}]</span>`;
});
document.getElementById('edgeList').innerHTML = edgeHtml;
document.getElementById('stepDisplay').textContent = curStep ? curStep.desc : 'Ready to start';
if (curStep && (curStep.type === 'complete' || curStep.type === 'cycle' || curStep.type === 'edge-count')) {
const isValid = curStep.valid === true || curStep.type === 'complete';
document.getElementById('resultArea').innerHTML = `
<div class="result ${isValid ? 'valid' : 'invalid'}">
${isValid ? '✅ Valid Tree!' : '❌ Not a Valid Tree'}
</div>`;
} else {
document.getElementById('resultArea').innerHTML = '';
}
}
reset();
</script>
</body>
</html>