-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
358 lines (320 loc) · 9.92 KB
/
script.js
File metadata and controls
358 lines (320 loc) · 9.92 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
const numRows = 20;
const numCols = 20;
const grid = [];
let startRow = null;
let startCol = null;
let endRow = null;
let endCol = null;
// Call the function to create the grid when the page loads
let obstacleState = true;
function createGrid() {
const gridElement = document.getElementById("grid");
for (let i = 0; i < numRows; i++) {
const newRow = [];
const row = document.createElement("tr");
for (let j = 0; j < numCols; j++) {
const cell = document.createElement("td");
cell.setAttribute("id", `${i}-${j}`);
newRow.push(0);
row.appendChild(cell);
cell.addEventListener("click", onGridCellClick);
cell.addEventListener("mouseenter", onGridCellMouseenter);
cell.addEventListener("dblclick", onGridCelldoubleClick);
}
grid.push(newRow);
gridElement.appendChild(row);
}
// Handling performance issue
gridElement.addEventListener("mouseleave", onGridMouseLeave);
}
window.onload = createGrid;
let startButton = document.getElementById("start-point-button");
let endButton = document.getElementById("end-point-button");
let obstaclesButton = document.getElementById("obstacle-button");
let RemoveObstacleButton = document.getElementById("remove-obstacle-button");
let Clear = document.getElementById("clear-button");
// events
startButton.addEventListener("click", function () {
onButtonClick("start-point-button");
});
endButton.addEventListener("click", function () {
onButtonClick("end-point-button");
});
obstaclesButton.addEventListener("click", function () {
onButtonClick("obstacle-button");
onObstacleButtonClick();
});
RemoveObstacleButton.addEventListener("click", function () {
onButtonClick("remove-obstacle-button");
});
Clear.addEventListener("click", function () {
location.reload();
});
function onButtonClick(id) {
const buttons = document.querySelectorAll(".button");
buttons.forEach((button) => {
button.classList.remove("active");
});
document.getElementById(id).classList.add("active");
}
function onGridCellClick(event) {
const cell = event.target;
if (
document.getElementById("start-point-button").classList.contains("active")
) {
const allCells = document.querySelectorAll("td");
allCells.forEach((cell) => {
cell.classList.remove("start");
});
cell.classList.add("start");
const [row, col] = cell.id.split("-").map(Number);
startRow = row;
startCol = col;
} else if (
document.getElementById("end-point-button").classList.contains("active")
) {
const allCells = document.querySelectorAll("td");
allCells.forEach((cell) => {
cell.classList.remove("end");
});
cell.classList.add("end");
const [row, col] = cell.id.split("-").map(Number);
endRow = row;
endCol = col;
} else if (
document
.getElementById("remove-obstacle-button")
.classList.contains("active")
) {
const [row, col] = cell.id.split("-").map(Number);
if (
!(
(row === startRow && col === startCol) ||
(row === endRow && col === endCol)
)
) {
grid[row][col] = 0;
cell.classList.remove("obstacle");
}
}
}
/****Handling Adding Obstacle****/
function onGridCellMouseenter(event) {
const cell = event.target;
if (
document.getElementById("obstacle-button").classList.contains("active") &&
obstacleState == true
) {
const [row, col] = cell.id.split("-").map(Number);
if (
!(
(row === startRow && col === startCol) ||
(row === endRow && col === endCol)
)
) {
grid[row][col] = 1;
cell.classList.add("obstacle");
}
}
}
function onGridCelldoubleClick() {
if (document.getElementById("obstacle-button").classList.contains("active"))
obstacleState = false;
}
function onGridMouseLeave() {
document.getElementById("obstacle-button").classList.remove("active");
}
function onObstacleButtonClick() {
obstacleState = true;
}
/************* Algo Buttons **********/
document.getElementById("bfs-button").addEventListener("click", function () {
onButtonClick("bfs-button");
runBFS();
});
document.getElementById("dfs-button").addEventListener("click", function () {
onButtonClick("dfs-button");
runDFS();
});
document
.getElementById("dijkstra-button")
.addEventListener("click", function () {
onButtonClick("dijkstra-button");
runDijkstra();
});
/***********BFS*********/
function runBFS() {
const visited = new Set();
const queue = [[startRow, startCol]];
function processQueue() {
if (queue.length === 0) {
return;
}
const [row, col] = queue.shift();
if (row === endRow && col === endCol) {
let currentRow = row;
let currentCol = col;
while (currentRow !== startRow || currentCol !== startCol) {
const cell = document.getElementById(`${currentRow}-${currentCol}`);
if (currentRow !== endRow || currentCol !== endCol)
cell.classList.add("path");
const [prevRow, prevCol] = JSON.parse(cell.dataset.prev);
currentRow = prevRow;
currentCol = prevCol;
}
return;
}
visited.add(`${row}-${col}`);
const neighbors = getNeighbors(row, col);
for (const [r, c] of neighbors) {
const key = `${r}-${c}`;
if (!visited.has(key) && grid[r][c] !== 1) {
visited.add(key);
queue.push([r, c]);
const cell = document.getElementById(`${r}-${c}`);
if (r !== endRow || c !== endCol) cell.classList.add("visited");
cell.dataset.prev = JSON.stringify([row, col]);
}
}
setTimeout(processQueue, 10);
}
processQueue();
}
/***********DFS*********/
function runDFS() {
const visited = new Set();
const stack = [[startRow, startCol]];
function processStack() {
// Prevent infinty Loops in there is no path , or no end cell
if (stack.length === 0) {
return;
}
const [row, col] = stack.pop();
if (row === endRow && col === endCol) {
let currentRow = row;
let currentCol = col;
while (currentRow !== startRow || currentCol !== startCol) {
const cell = document.getElementById(`${currentRow}-${currentCol}`);
if (currentRow !== endRow || currentCol !== endCol)
cell.classList.add("path");
const [prevRow, prevCol] = JSON.parse(cell.dataset.prev);
currentRow = prevRow;
currentCol = prevCol;
}
return;
}
visited.add(`${row}-${col}`);
const neighbors = getNeighbors(row, col);
for (const [r, c] of neighbors) {
const key = `${r}-${c}`;
if (!visited.has(key) && grid[r][c] !== 1) {
visited.add(key);
stack.push([r, c]);
const cell = document.getElementById(`${r}-${c}`);
if (r !== endRow || c !== endCol) cell.classList.add("visited");
cell.dataset.prev = JSON.stringify([row, col]);
}
// No need to continue exploring neighbor cells if you have reached the End Cell
if (r == endRow && c == endCol) {
while (stack.isEmpty === false) stack.pop();
stack.push([r, c]);
break;
}
}
setTimeout(processStack, 10);
}
processStack();
}
/***********Dijkstra************/
function runDijkstra() {
const distances = {};
const visited = new Set();
const pq = new PriorityQueue();
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
distances[`${i}-${j}`] = Infinity;
}
}
distances[`${startRow}-${startCol}`] = 0;
pq.push(`${startRow}-${startCol}`, 0);
function processStep() {
if (pq.isEmpty() || visited.size === numRows * numCols) {
return;
}
const current = pq.pop().element;
const [row, col] = current.split("-").map(Number);
if (visited.has(current)) return;
visited.add(current);
if (row === endRow && col === endCol) {
let currentRow = row;
let currentCol = col;
while (currentRow !== startRow || currentCol !== startCol) {
const cell = document.getElementById(`${currentRow}-${currentCol}`);
if (currentRow !== endRow || currentCol !== endCol)
cell.classList.add("path");
const [prevRow, prevCol] = JSON.parse(cell.dataset.prev);
currentRow = prevRow;
currentCol = prevCol;
}
return;
}
const neighbors = getNeighbors(row, col);
for (const [r, c] of neighbors) {
if (!visited.has(`${r}-${c}`) && grid[r][c] !== 1) {
const distance = distances[`${row}-${col}`] + 1;
if (distance < distances[`${r}-${c}`]) {
distances[`${r}-${c}`] = distance;
pq.push(`${r}-${c}`, distance);
const cell = document.getElementById(`${r}-${c}`);
if (r !== endRow || c !== endCol) cell.classList.add("visited");
cell.dataset.prev = JSON.stringify([row, col]);
}
}
// give the highest priority to end cell , no need to explore more cells
if (r === endRow && c === endCol) {
pq.push(`${r}-${c}`, -1);
break;
}
}
setTimeout(processStep, 10);
}
processStep();
}
function getNeighbors(row, col) {
const neighbors = [];
if (row > 0) neighbors.push([row - 1, col]);
if (row < numRows - 1) neighbors.push([row + 1, col]);
if (col > 0) neighbors.push([row, col - 1]);
if (col < numCols - 1) neighbors.push([row, col + 1]);
return neighbors;
}
/**PriorityQueue Implmentation**/
class PriorityQueue {
constructor() {
this.elements = {};
this.priorities = {};
}
push(element, priority) {
this.elements[element] = true;
this.priorities[element] = priority;
}
pop() {
let minPriority = Infinity;
let minElement = null;
for (const element in this.elements) {
if (this.priorities[element] < minPriority) {
minPriority = this.priorities[element];
minElement = element;
}
}
if (minElement !== null) {
delete this.elements[minElement];
delete this.priorities[minElement];
return { element: minElement, priority: minPriority };
}
return null;
}
isEmpty() {
return Object.keys(this.elements).length === 0;
}
}