gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Покажи пример Ада Колбеков на Js
- User
Покажи пример Ада Колбеков на Js
- Assistant
Покажи пример Ада Колбеков на Js
Конечно! Ниже представлен пример реализации алгоритма A* (А-star) на JavaScript. Алгоритм A* используется для поиска кратчайшего пути на графах, например, в играх или схемах городов.
Пример кода реализует A* для нахождения пути на двумерной решетке:
class Node {
constructor(x, y, cost, heuristic) {
this.x = x; // Позиция по оси X
this.y = y; // Позиция по оси Y
this.cost = cost; // Расстояние от начальной точки
this.heuristic = heuristic; // Оценка расстояния до цели
this.totalCost = cost + heuristic; // Общая стоимость
this.parent = null; // Узел родитель
}
}
// Функция для оценки расстояния (эвристики)
function heuristic(a, b) {
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
// Функция A*
function astar(grid, start, end) {
const openSet = [];
const closedSet = new Set();
openSet.push(new Node(start.x, start.y, 0, heuristic(start, end)));
while (openSet.length > 0) {
// Находим узел с наименьшей общей стоимостью
openSet.sort((a, b) => a.totalCost - b.totalCost);
const current = openSet.shift();
// Если достигли цели
if (current.x === end.x && current.y === end.y) {
const path = [];
let temp = current;
while (temp) {
path.push({ x: temp.x, y: temp.y });
temp = temp.parent;
}
return path.reverse(); // Возвращаем путь от начальной до конечной точки
}
closedSet.add(`${current.x},${current.y}`);
// Проверяем соседей
const neighbors = [
{ x: current.x - 1, y: current.y },
{ x: current.x + 1, y: current.y },
{ x: current.x, y: current.y - 1 },
{ x: current.x, y: current.y + 1 }
];
for (const neighbor of neighbors) {
if (
neighbor.x < 0 || neighbor.y < 0 ||
neighbor.x >= grid.length || neighbor.y >= grid[0].length ||
grid[neighbor.x][neighbor.y] === 1 || // Препятствие
closedSet.has(`${neighbor.x},${neighbor.y}`)
) {
continue; // Пропускаем препятствия и закрытые узлы
}
const tentativeCost = current.cost + 1; // Расстояние до соседа
const existingNode = openSet.find(node => node.x === neighbor.x && node.y === neighbor.y);
if (!existingNode || tentativeCost < existingNode.cost) {
const newNode = new Node(neighbor.x, neighbor.y, tentativeCost, heuristic(neighbor, end));
newNode.parent = current;
if (!existingNode) {
openSet.push(newNode);
} else {
existingNode.parent = current; // Обновляем родителя
}
}
}
}
return []; // Возвращаем пустой массив, если путь не найден
}
// Пример использования
const grid = [
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]
];
const start = { x: 0, y: 0 };
const end = { x: 4, y: 4 };
const path = astar(grid, start, end);
console.log(path); // Выводим путь
В этом примере:
Node представляет собой узел графа.heuristic вычисляет манхэттенское расстояние.astar реализует сам алгоритм A* и находит кратчайший путь между start и end на решетке grid.Препятствия в решетке обозначены значением 1, тогда как проходимые клетки — 0. Результат будет массивом объектов, представляющих координаты клеток на пути от начальной до конечной точки.
Not yet included in a published release.