forked from jambis-prg/real-time-pathfinding-simulation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.js
More file actions
48 lines (40 loc) · 1.46 KB
/
Copy pathDFS.js
File metadata and controls
48 lines (40 loc) · 1.46 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
class DFS extends PathAlgorithm {
constructor() {
super();
this.stack = []; // fronteira da busca (LIFO)
}
// inicializa o estado da busca
init(grid, start, goal) {
super.init(grid, start, goal); // define grid, start e goal na classe pai
this.grid.clear(); // limpa o mapa de visitados anterior
this.stack = [start]; // inicia a fronteira com o ponto inicial
// armazena o nó inicial como visitado com um marcador de raiz (-1)
this.grid.visit(start, -1);
}
// executa um passo da busca por iteração (para animação)
step() {
// se a pilha estiver vazia ou já finalizou, não faz nada
if (this.stack.length === 0 || this.finished) {
this.finished = true;
return true;
}
// DFS remove o último elemento adicionado (Pilha/LIFO)
let current = this.stack.pop();
// verifica se alcançou o objetivo
if (current === this.goal) {
this.finished = true;
return true;
}
// obtém vizinhos válidos (dentro dos limites e não paredes)
let neighbors = this.grid.neighbors(current);
for (let neighbor of neighbors) {
// se o vizinho ainda não foi explorado
if (!this.grid.hasVisited(neighbor)) {
this.grid.visit(neighbor, current); // registra a visita e o pai para reconstruir o caminho
this.stack.push(neighbor); // adiciona na fronteira para exploração profunda
}
}
this.grid.frontier = [...this.stack];
return false;
}
}