-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.html
More file actions
381 lines (337 loc) · 10.9 KB
/
dfs.html
File metadata and controls
381 lines (337 loc) · 10.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Graph DFS Visualizer - Multiple Graphs with Explanation</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
#explanation {
background: #1e293b;
border-radius: 0.5rem;
padding: 1rem;
height: 220px;
overflow-y: auto;
font-family: monospace;
white-space: pre-wrap;
line-height: 1.5;
font-size: 15px;
margin-top: 1rem;
box-shadow: inset 0 0 8px #334155;
}
/* Typewriter effect cursor */
.cursor {
display: inline-block;
background-color: #3b82f6;
width: 8px;
animation: blink 1s infinite;
vertical-align: bottom;
margin-left: 2px;
border-radius: 2px;
}
@keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
</style>
</head>
<body class="bg-gray-900 text-white min-h-screen flex items-center justify-center p-4">
<div class="p-6 bg-gray-800 rounded-xl shadow-xl w-[1400px] max-w-full">
<div class="flex gap-6 flex-wrap">
<!-- Sidebar -->
<div class="w-64 flex flex-col gap-4">
<h2 class="text-2xl font-bold mb-2">DFS Visualizer (Multiple Graphs)</h2>
<label>
Start Node:
<select id="start" class="w-full text-black rounded p-2 mt-1"></select>
</label>
<button id="run" class="bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded">Run DFS</button>
<button id="reset" class="bg-gray-400 hover:bg-gray-500 text-white py-2 px-4 rounded">Reset</button>
<button id="changeGraph" class="bg-green-600 hover:bg-green-700 text-white py-2 px-4 rounded">Change Graph</button>
<button id="playPause" class="bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded mt-2">Play</button>
<p id="orderDisplay" class="text-sm text-gray-300 mt-4">DFS Order: </p>
<p id="graphName" class="text-gray-400 mt-2"></p>
<div id="explanation" tabindex="0" aria-label="DFS explanation text" role="log" aria-live="polite"></div>
</div>
<!-- Graph Area -->
<div class="flex-1 overflow-auto max-w-[1100px]">
<svg id="graph" width="1100" height="700" class="rounded bg-gray-700 shadow"></svg>
</div>
</div>
</div>
<script>
const graphs = [
{
name: "Binary Tree (31 nodes)",
totalNodes: 31,
positions: (() => {
const positions = [];
const levels = 5;
const width = 1100;
const verticalSpacing = 110;
for (let level = 0; level < levels; level++) {
const nodesInLevel = Math.pow(2, level);
const horizontalSpacing = width / (nodesInLevel + 1);
for (let i = 0; i < nodesInLevel; i++) {
const x = horizontalSpacing * (i + 1);
const y = verticalSpacing * level + 50;
positions.push({ x, y });
}
}
return positions;
})(),
edges: (() => {
const edges = [];
const totalNodes = 31;
for (let i = 0; i < totalNodes; i++) {
const left = 2 * i + 1;
const right = 2 * i + 2;
if (left < totalNodes) edges.push([i, left]);
if (right < totalNodes) edges.push([i, right]);
}
return edges;
})()
},
{
name: "Grid Graph (5x5 = 25 nodes)",
totalNodes: 25,
positions: (() => {
const positions = [];
const rows = 5;
const cols = 5;
const spacingX = 180;
const spacingY = 120;
const startX = 100;
const startY = 100;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
positions.push({ x: startX + c * spacingX, y: startY + r * spacingY });
}
}
return positions;
})(),
edges: (() => {
const edges = [];
const rows = 5;
const cols = 5;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const idx = r * cols + c;
// right neighbor
if (c + 1 < cols) edges.push([idx, idx + 1]);
// down neighbor
if (r + 1 < rows) edges.push([idx, idx + cols]);
}
}
return edges;
})()
}
];
let currentGraphIndex = 0;
let graph = graphs[currentGraphIndex];
let adj = [];
let animOrder = [];
let visitedEdges = new Set();
const radius = 18;
let play = false;
let pauseResolve = null;
function buildAdjacency() {
adj = Array.from({ length: graph.totalNodes }, () => []);
graph.edges.forEach(([u, v]) => {
adj[u].push(v);
adj[v].push(u);
});
}
function drawGraph() {
const svg = document.getElementById("graph");
svg.innerHTML = "";
for (let [u, v] of graph.edges) {
const p1 = graph.positions[u];
const p2 = graph.positions[v];
const edgeId1 = `${u}-${v}`;
const edgeId2 = `${v}-${u}`;
const isVisitedEdge = visitedEdges.has(edgeId1) || visitedEdges.has(edgeId2);
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute("x1", p1.x);
line.setAttribute("y1", p1.y);
line.setAttribute("x2", p2.x);
line.setAttribute("y2", p2.y);
line.setAttribute("stroke", isVisitedEdge ? "#3b82f6" : "#ccc");
line.setAttribute("stroke-width", isVisitedEdge ? "5" : "2");
svg.appendChild(line);
}
// Draw nodes
for (let i = 0; i < graph.totalNodes; i++) {
const { x, y } = graph.positions[i];
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", x);
circle.setAttribute("cy", y);
circle.setAttribute("r", radius);
circle.setAttribute("fill", animOrder.includes(i) ? "#3b82f6" : "#e2e8f0");
circle.setAttribute("stroke", "#1e293b");
circle.setAttribute("stroke-width", "2");
svg.appendChild(circle);
const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
text.setAttribute("x", x);
text.setAttribute("y", y + 6);
text.setAttribute("text-anchor", "middle");
text.setAttribute("font-size", "16");
text.setAttribute("font-weight", "bold");
text.setAttribute("fill", animOrder.includes(i) ? "#fff" : "#000");
text.textContent = i;
svg.appendChild(text);
}
}
function fillSelects() {
const startSel = document.getElementById("start");
startSel.innerHTML = "";
for (let i = 0; i < graph.totalNodes; i++) {
const opt = document.createElement("option");
opt.value = i;
opt.textContent = i;
startSel.appendChild(opt);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// --- TYPEWRITER FUNCTION ---
// Types out the given text letter by letter inside the given element
async function typeWriterEffect(element, text, speed = 20) {
element.textContent = ""; // clear
for (let i = 0; i < text.length; i++) {
// Wait if paused
await waitIfPaused();
element.textContent += text.charAt(i);
// Add blinking cursor effect:
// We'll add a span cursor after text, removed/readded to simulate blinking
if (!element.querySelector(".cursor")) {
const cursor = document.createElement("span");
cursor.className = "cursor";
element.appendChild(cursor);
}
await sleep(speed);
}
// Remove cursor after done typing
const cursor = element.querySelector(".cursor");
if (cursor) cursor.remove();
}
// Waits if play = false, resolves when play = true
function waitIfPaused() {
if (play) return Promise.resolve();
return new Promise(resolve => (pauseResolve = resolve));
}
// Resolves pause when toggled play on
function resumeIfPaused() {
if (pauseResolve) {
pauseResolve();
pauseResolve = null;
}
}
const explanationContainer = document.getElementById("explanation");
function appendExplanationLine(text) {
const line = document.createElement("div");
explanationContainer.appendChild(line);
// Scroll to bottom after next frame
setTimeout(() => {
explanationContainer.scrollTop = explanationContainer.scrollHeight;
}, 50);
return line;
}
async function runDFS(start) {
const visited = Array(graph.totalNodes).fill(false);
animOrder = [];
visitedEdges.clear();
explanationContainer.innerHTML = ""; // clear explanations on new run
updateOrderDisplay();
async function dfs(u) {
// Explanation line for visiting node
let line = appendExplanationLine(`Visiting node ${u}...`);
await typeWriterEffect(line, `Visiting node ${u}...`, 30);
visited[u] = true;
animOrder.push(u);
drawGraph();
updateOrderDisplay();
await sleep(400);
for (const v of adj[u]) {
if (!visited[v]) {
// Explain edge traversal
line = appendExplanationLine(`Going deeper from node ${u} to ${v}...`);
await typeWriterEffect(line, `Going deeper from node ${u} to ${v}...`, 30);
visitedEdges.add(`${u}-${v}`);
drawGraph();
await sleep(400);
await dfs(v);
} else {
// Explain skipping visited
line = appendExplanationLine(`Node ${v} already visited, skipping...`);
await typeWriterEffect(line, `Node ${v} already visited, skipping...`, 30);
await sleep(300);
}
}
// After exploring all neighbors
line = appendExplanationLine(`Backtracking from node ${u}...`);
await typeWriterEffect(line, `Backtracking from node ${u}...`, 30);
await sleep(300);
}
await dfs(start);
const doneLine = appendExplanationLine("DFS Complete!");
await typeWriterEffect(doneLine, "DFS Complete!", 30);
play = false;
updatePlayPauseButton();
}
function updateOrderDisplay() {
document.getElementById("orderDisplay").textContent = `DFS Order: ${animOrder.join(" → ")}`;
document.getElementById("graphName").textContent = `Current Graph: ${graph.name}`;
}
function resetAll() {
animOrder = [];
visitedEdges.clear();
explanationContainer.innerHTML = "";
drawGraph();
updateOrderDisplay();
play = false;
updatePlayPauseButton();
resumeIfPaused();
}
function updatePlayPauseButton() {
const btn = document.getElementById("playPause");
btn.textContent = play ? "Pause" : "Play";
}
document.addEventListener("DOMContentLoaded", () => {
buildAdjacency();
fillSelects();
drawGraph();
updateOrderDisplay();
document.getElementById("run").onclick = async () => {
if (play) return; // Prevent double run
animOrder = [];
visitedEdges.clear();
play = true;
updatePlayPauseButton();
const start = +document.getElementById("start").value;
await runDFS(start);
};
document.getElementById("reset").onclick = () => {
resetAll();
};
document.getElementById("changeGraph").onclick = () => {
currentGraphIndex = (currentGraphIndex + 1) % graphs.length;
graph = graphs[currentGraphIndex];
animOrder = [];
visitedEdges.clear();
buildAdjacency();
fillSelects();
resetAll();
};
document.getElementById("playPause").onclick = () => {
play = !play;
updatePlayPauseButton();
if (play) {
resumeIfPaused();
}
};
});
</script>
</body>
</html>