-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.html
More file actions
396 lines (354 loc) · 11 KB
/
bfs.html
File metadata and controls
396 lines (354 loc) · 11 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>BFS Visualizer with Play/Pause & Accumulating Explanation</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
#explanationContainer {
white-space: pre-wrap;
font-family: monospace;
font-size: 0.875rem;
max-height: 220px;
overflow-y: auto;
background: #111827;
padding: 0.75rem;
border-radius: 0.375rem;
color: #d1d5db;
}
</style>
</head>
<body class="bg-gray-900 text-white min-h-screen flex items-center justify-center">
<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">BFS Visualizer (Multiple Graphs)</h2>
<label>
Start Node:
<select id="start" class="w-full text-black rounded p-2 mt-1"></select>
</label>
<div class="flex gap-2">
<button id="playPause" class="bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded flex-1">Play</button>
<button id="reset" class="bg-gray-400 hover:bg-gray-500 text-white py-2 px-4 rounded flex-1">Reset</button>
</div>
<button id="changeGraph" class="bg-green-700 hover:bg-green-800 text-white py-2 px-4 rounded">Change Graph</button>
<p id="orderDisplay" class="text-sm text-gray-300 mt-4">BFS Order: </p>
<p id="graphName" class="text-gray-400 mt-2"></p>
<div class="mt-4 flex flex-col gap-2">
<h3 class="font-semibold">Explanation Steps:</h3>
<div id="explanationContainer"></div>
</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;
if (c + 1 < cols) edges.push([idx, idx + 1]);
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 isRunning = false;
let isPaused = true; // initially paused until Play is clicked
let bfsGenerator = null;
let currentTimeout = 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 = "";
// Draw edges
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 effect: appends text char-by-char to the explanation container with abort support
async function typeWriter(text, container, delay = 40, abortSignal) {
return new Promise(async (resolve, reject) => {
if (!text) {
resolve();
return;
}
let i = 0;
const chars = text.split("");
while (i < chars.length) {
if (abortSignal.aborted) {
reject(new Error("Cancelled"));
return;
}
container.textContent += chars[i];
container.scrollTop = container.scrollHeight;
i++;
await sleep(delay);
}
container.textContent += "\n";
container.scrollTop = container.scrollHeight;
resolve();
});
}
// BFS generator yields explanation steps
function* bfsGen(start) {
const visited = Array(graph.totalNodes).fill(false);
const queue = [];
animOrder = [];
visitedEdges.clear();
yield `Starting BFS from node ${start}.`;
queue.push(start);
visited[start] = true;
while (queue.length > 0) {
const u = queue.shift();
yield `Dequeued node ${u} for processing.`;
animOrder.push(u);
yield null; // redraw step indicator (no explanation text)
for (const v of adj[u]) {
if (!visited[v]) {
visitedEdges.add(`${u}-${v}`);
yield `Visiting node ${v} from node ${u}, marking it as visited and adding to queue.`;
visited[v] = true;
queue.push(v);
animOrder.push(v);
yield null; // redraw
} else {
yield `Node ${v} already visited, skipping.`;
}
}
}
yield "BFS traversal completed.";
}
function updateOrderDisplay() {
document.getElementById("orderDisplay").textContent = `BFS Order: ${animOrder.join(" → ")}`;
document.getElementById("graphName").textContent = `Current Graph: ${graph.name}`;
}
function resetSimulation() {
isRunning = false;
isPaused = true;
animOrder = [];
visitedEdges.clear();
bfsGenerator = null;
clearTimeout(currentTimeout);
currentTimeout = null;
// Reset UI states
document.getElementById("playPause").textContent = "Play";
document.getElementById("explanationContainer").textContent = "";
drawGraph();
updateOrderDisplay();
}
async function animateBFS(start) {
isRunning = true;
isPaused = false;
document.getElementById("playPause").textContent = "Pause";
bfsGenerator = bfsGen(start);
const explanationContainer = document.getElementById("explanationContainer");
const abortController = new AbortController();
async function step() {
if (!isRunning || isPaused) {
// Wait a bit and re-check if resumed
currentTimeout = setTimeout(step, 200);
return;
}
const { value, done } = bfsGenerator.next();
if (done) {
isRunning = false;
document.getElementById("playPause").textContent = "Play";
return;
}
if (value !== null) {
try {
await typeWriter(value.trim(), explanationContainer, 40, abortController.signal);
} catch {
// Cancelled - stop further animation
return;
}
}
drawGraph();
updateOrderDisplay();
// Next step after delay (shorter if no text)
const delay = (value === null) ? 600 : 1000;
currentTimeout = setTimeout(step, delay);
}
step();
// Return abortController to cancel if needed
return abortController;
}
let currentAbortController = null;
document.addEventListener("DOMContentLoaded", () => {
buildAdjacency();
fillSelects();
drawGraph();
updateOrderDisplay();
const playPauseBtn = document.getElementById("playPause");
const resetBtn = document.getElementById("reset");
const changeGraphBtn = document.getElementById("changeGraph");
playPauseBtn.onclick = () => {
if (!isRunning) {
// Start animation
const start = +document.getElementById("start").value;
animateBFS(start).then(controller => {
currentAbortController = controller;
});
} else if (isPaused) {
// Resume
isPaused = false;
playPauseBtn.textContent = "Pause";
} else {
// Pause
isPaused = true;
playPauseBtn.textContent = "Play";
}
};
resetBtn.onclick = () => {
if (isRunning) {
isRunning = false;
isPaused = true;
if (currentAbortController) currentAbortController.abort();
currentAbortController = null;
clearTimeout(currentTimeout);
currentTimeout = null;
}
resetSimulation();
};
changeGraphBtn.onclick = () => {
if (isRunning) {
isRunning = false;
isPaused = true;
if (currentAbortController) currentAbortController.abort();
currentAbortController = null;
clearTimeout(currentTimeout);
currentTimeout = null;
}
currentGraphIndex = (currentGraphIndex + 1) % graphs.length;
graph = graphs[currentGraphIndex];
buildAdjacency();
fillSelects();
resetSimulation();
};
});
</script>
</body>
</html>