-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdj.html
More file actions
344 lines (305 loc) · 10.6 KB
/
Copy pathdj.html
File metadata and controls
344 lines (305 loc) · 10.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Dijkstra Visualizer</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
#explanation {
scrollbar-width: thin;
scrollbar-color: #60a5fa #1e293b;
}
#explanation::-webkit-scrollbar {
width: 8px;
}
#explanation::-webkit-scrollbar-thumb {
background-color: #60a5fa;
border-radius: 4px;
}
@media (max-width: 1100px) {
.container-flex {
flex-direction: column;
}
#graph {
width: 100% !important;
height: 500px !important;
margin-top: 16px;
}
.sidebar {
width: 100% !important;
max-width: none !important;
margin-bottom: 16px;
}
}
</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-full max-w-[1400px] flex container-flex gap-6 flex-wrap">
<!-- Sidebar -->
<div class="sidebar w-64 flex flex-col gap-4 flex-shrink-0">
<h2 class="text-2xl font-bold mb-2">Dijkstra Visualizer</h2>
<label>
Start Node:
<select id="start" class="w-full text-black rounded p-2 mt-1"></select>
</label>
<label>
End Node:
<select id="end" 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</button>
<button id="reset" class="bg-gray-400 hover:bg-gray-500 text-white py-2 px-4 rounded">Reset</button>
<button id="toggle" class="bg-yellow-500 hover:bg-yellow-600 text-white py-2 px-4 rounded">Pause</button>
<p id="pathDisplay" class="text-sm text-gray-300 mt-2">Shortest Path: </p>
<div id="explanation" class="text-sm text-blue-300 mt-2 max-h-80 overflow-auto p-2 bg-gray-900 rounded"></div>
</div>
<div class="flex-1 min-w-[300px]">
<svg id="graph" width="1000" height="700" class="rounded bg-gray-700 shadow w-full h-[700px]"></svg>
</div>
</div>
<script>
const positions = [
{x: 100, y: 350}, {x: 200, y: 250}, {x: 200, y: 450},
{x: 300, y: 350}, {x: 400, y: 150}, {x: 400, y: 350},
{x: 400, y: 550}, {x: 600, y: 250}, {x: 600, y: 450}, {x: 750, y: 350},
];
const edges = [
[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3], [2, 6],
[3, 4], [3, 5], [3, 6], [4, 5], [4, 7], [5, 6], [5, 7], [5, 8], [6, 8], [7, 9], [8, 9]
];
// Create adjacency matrix with weights
let graph = Array.from({ length: 10 }, () => Array(10).fill(Infinity));
edges.forEach(([u, v]) => {
const w = Math.floor(Math.random() * 20) + 5;
graph[u][v] = w;
graph[v][u] = w;
});
class PriorityQueue {
constructor() { this.data = []; }
enqueue(val, pri) {
this.data.push({ val, pri });
this.data.sort((a, b) => a.pri - b.pri);
}
dequeue() { return this.data.shift()?.val; }
isEmpty() { return this.data.length === 0; }
}
let animPath = [];
let distMemory = [];
let isPaused = false;
let toggleBtn;
function sleep(ms) {
return new Promise(resolve => {
const check = () => {
if (!isPaused) {
resolve();
} else {
setTimeout(check, 100);
}
};
setTimeout(check, ms);
});
}
async function typeExplanation(text) {
const explanationDiv = document.getElementById("explanation");
return new Promise(async (resolve) => {
let para = document.createElement("p");
explanationDiv.appendChild(para);
for (let i = 0; i < text.length; i++) {
while (isPaused) {
await sleep(100);
}
para.textContent += text[i];
explanationDiv.scrollTop = explanationDiv.scrollHeight;
await sleep(80); // Slowed down here from 40ms to 80ms
}
resolve();
});
}
function drawGraph(highlightedEdges = [], distMap = [], currentNode = null, finalHighlight = false) {
const svg = document.getElementById("graph");
svg.innerHTML = "";
// Draw edges
for (let [u, v] of edges) {
const p1 = positions[u];
const p2 = positions[v];
const isHighlighted = highlightedEdges.includes(`${u}-${v}`) || highlightedEdges.includes(`${v}-${u}`);
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", isHighlighted ? "#3b82f6" : "#ccc");
line.setAttribute("stroke-width", isHighlighted ? "5" : "2");
line.setAttribute("opacity", isHighlighted ? "1" : "0.6");
svg.appendChild(line);
// Edge weight label with offset
const midX = (p1.x + p2.x) / 2;
const midY = (p1.y + p2.y) / 2;
const dx = p2.y - p1.y;
const dy = p1.x - p2.x;
const len = Math.sqrt(dx * dx + dy * dy);
const offset = 12;
const tx = midX + (dx / len) * offset;
const ty = midY + (dy / len) * offset;
const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
text.setAttribute("x", tx);
text.setAttribute("y", ty);
text.setAttribute("fill", "#38bdf8");
text.setAttribute("font-size", "14");
text.setAttribute("text-anchor", "middle");
text.setAttribute("font-weight", "bold");
text.textContent = graph[u][v];
svg.appendChild(text);
}
// Draw nodes
for (let i = 0; i < positions.length; i++) {
const {x, y} = positions[i];
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", x);
circle.setAttribute("cy", y);
circle.setAttribute("r", 22);
if (animPath.includes(i)) {
circle.setAttribute("fill", "#2563eb"); // visited nodes blue
} else if (currentNode === i) {
circle.setAttribute("fill", "#facc15"); // current node yellow
} else {
circle.setAttribute("fill", "#e2e8f0"); // default nodes
}
circle.setAttribute("stroke", "#1e293b");
circle.setAttribute("stroke-width", "3");
svg.appendChild(circle);
// Node label (number)
const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
text.setAttribute("x", x);
text.setAttribute("y", y + 7);
text.setAttribute("text-anchor", "middle");
text.setAttribute("font-size", "18");
text.setAttribute("font-weight", "bold");
text.setAttribute("fill", animPath.includes(i) || currentNode === i ? "#fff" : "#000");
text.textContent = i;
svg.appendChild(text);
// Distance display above node if known
if (distMap[i] !== undefined && distMap[i] !== Infinity) {
const distText = document.createElementNS("http://www.w3.org/2000/svg", "text");
distText.setAttribute("x", x);
distText.setAttribute("y", y - 30);
distText.setAttribute("text-anchor", "middle");
distText.setAttribute("font-size", "14");
// Final distances green, otherwise blue
distText.setAttribute("fill", finalHighlight ? "#4ade80" : "#38bdf8");
distText.textContent = `d: ${distMap[i]}`;
svg.appendChild(distText);
}
}
}
async function runDijkstraStepByStep(start, end) {
const dist = Array(positions.length).fill(Infinity);
const prev = Array(positions.length).fill(null);
const visited = Array(positions.length).fill(false);
const pq = new PriorityQueue();
dist[start] = 0;
pq.enqueue(start, 0);
animPath = [];
distMemory = [];
document.getElementById("explanation").innerHTML = "";
await typeExplanation(`Starting from node ${start}. Set d[${start}] = 0. All other nodes are at infinity (∞).`);
drawGraph([], dist, start);
await sleep(1000);
while (!pq.isEmpty()) {
const u = pq.dequeue();
if (visited[u]) continue;
visited[u] = true;
animPath.push(u);
await typeExplanation(`\nExploring node ${u}.`);
drawGraph([], dist, u);
await sleep(800);
for (let v = 0; v < positions.length; v++) {
if (graph[u][v] !== Infinity && !visited[v]) {
const alt = dist[u] + graph[u][v];
if (alt < dist[v]) {
await typeExplanation(`\nFound shorter path to node ${v}: updating d[${v}] from ${dist[v] === Infinity ? '∞' : dist[v]} to ${alt} via node ${u}.`);
dist[v] = alt;
prev[v] = u;
pq.enqueue(v, alt);
drawGraph([], dist, u);
await sleep(800);
} else {
await typeExplanation(`\nNode ${v} already has a shorter distance d[${v}] = ${dist[v]}, so no update needed.`);
}
}
}
drawGraph([], dist, u);
await sleep(800);
}
distMemory = dist.slice();
// Show final distances in green
drawGraph([], distMemory, null, true);
// Build path from end to start
const path = [];
for (let at = end; at !== null; at = prev[at]) {
path.push(at);
}
path.reverse();
if (path[0] === start) {
let cost = 0;
for (let i = 1; i < path.length; i++) cost += graph[path[i - 1]][path[i]];
document.getElementById("pathDisplay").textContent =
`Shortest Path: ${path.join(" → ")} (Total Cost: ${cost})`;
await animateFinalPath(path);
} else {
document.getElementById("pathDisplay").textContent = "No path found.";
}
}
async function animateFinalPath(path) {
let index = 1;
const highlightedEdges = [];
animPath = [path[0]];
drawGraph(highlightedEdges, distMemory, path[0], true);
while (index < path.length) {
highlightedEdges.push(`${path[index - 1]}-${path[index]}`);
animPath.push(path[index]);
drawGraph(highlightedEdges, distMemory, path[index], true);
await sleep(1000);
index++;
}
}
function fillSelects() {
const startSel = document.getElementById("start");
const endSel = document.getElementById("end");
for (let i = 0; i < positions.length; i++) {
const opt1 = document.createElement("option");
opt1.value = i;
opt1.textContent = i;
const opt2 = opt1.cloneNode(true);
startSel.appendChild(opt1);
endSel.appendChild(opt2);
}
endSel.value = positions.length - 1;
}
document.addEventListener("DOMContentLoaded", () => {
fillSelects();
drawGraph();
toggleBtn = document.getElementById("toggle");
toggleBtn.onclick = () => {
isPaused = !isPaused;
toggleBtn.textContent = isPaused ? "Play" : "Pause";
};
document.getElementById("run").onclick = () => {
if (isPaused) {
isPaused = false;
toggleBtn.textContent = "Pause";
}
animPath = [];
document.getElementById("explanation").innerHTML = "";
document.getElementById("pathDisplay").textContent = "Shortest Path: ";
const start = +document.getElementById("start").value;
const end = +document.getElementById("end").value;
runDijkstraStepByStep(start, end);
};
document.getElementById("reset").onclick = () => {
location.reload();
};
});
</script>
</body>
</html>