forked from jambis-prg/real-time-pathfinding-simulation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGreedy.js
More file actions
58 lines (46 loc) · 1.58 KB
/
Copy pathGreedy.js
File metadata and controls
58 lines (46 loc) · 1.58 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
class Greedy extends PathAlgorithm {
constructor() {
super();
this.parent = new Map();
this.queue = [];
this.visited = new Set();
}
init(grid, start, goal) {
super.init(grid, start, goal);
// Limpa as estruturas específicas do Greedy
this.parent.clear();
this.visited.clear();
this.queue = [];
// Configuração inicial: empilha o start com sua heurística até o goal
this.queue.push({ node: start, h: this.grid.heuristic(start, goal) });
}
step() {
if (this.queue.length === 0) {
this.finished = true;
return true;
}
// Fila de prioridade: ordena para processar sempre o menor h(n)
// O guloso ignora o custo acumulado g(n) e usa apenas a heurística
this.queue.sort((a, b) => b.h - a.h);
let { node } = this.queue.pop();
if (this.visited.has(node)) return false;
this.visited.add(node);
// Registra no grid para desenho do rastro e reconstrução do caminho
this.grid.visit(node, this.parent.get(node) ?? -1);
// Chegou ao objetivo
if (node === this.goal) {
this.finished = true;
return true;
}
// Expande vizinhos: descoberta única (sem relaxamento, diferente do A*)
let neighbors = this.grid.neighbors(node);
for (let neighbor of neighbors) {
if (this.visited.has(neighbor) || this.parent.has(neighbor)) continue;
this.parent.set(neighbor, node);
let h = this.grid.heuristic(neighbor, this.goal);
this.queue.push({ node: neighbor, h: h });
}
this.grid.frontier = this.queue.map(item => item.node);
return false;
}
}