JavaScript实现AStar算法

本文介绍了一个使用JavaScript实现的AStar寻路算法。通过定义AStar类及其方法,包括点对象构造、距离计算、节点操作、路径获取等,实现了在给定地图上寻找从起点到终点的最短路径。示例代码展示了如何加载地图、搜索路径并显示在表格中,以及用户交互功能,允许点击地图设置起点和终点。
摘要由CSDN通过智能技术生成

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>A-Star</title>
<script type="text/javascript">
/*
蛮好玩的东西。。。
严重感谢winter。。。
*/

var AStar = function () {
    this.tmin = -1;   //上部搜索最小值(不包括)
    this.rmax = -1;   //右部搜索最大值(不包括)
    this.bmax = -1;   //下部搜索最大值(不包括)
    this.lmin = -1;   //左部搜索最小值(不包括)
    this.initialize();
};

AStar.prototype = {

    constructor : AStar
   
    , pointSource : function () {
    //获取点对象构造的引用
        return this.constructor.Point;
    }
   
    , euclidean : function (a, b) {
        with (Math) { return round(10 * sqrt(pow(a.X - b.X, 2) + pow(a.Y - b.Y, 2))); }
    }
   
    , manhattan : function (a, b) {
        with (Math) { return abs(a.X - b.X) + abs(a.Y - b.Y); }
    }
   
    , initialize : function () {
    //初始化参数
        this.open = [];   //open表
        this.close = [];  //close表
        this.maps = {};  //已经发现点组
    }
   
    , makeID : function (x, y, limit) {
    //创造ID
        return x + y * limit;
    }
   
    , getMinNode : function () {
    //获取最佳节点
        var i = 1, o = this.open, l = o.length, min = i - 1, max = o[0].F, t = null;

        for (; i < l ; i ++) {
            t = o[i];
            if (t.F < max) { max = t.F, min = i; }
        }
        t = o[min], o[min] = o[l - 1], o.pop();

        return t;
    }
   
    , getNodes : function (node) {
    //获取子节点
        var map = this.Map, tmin = this.tmin, rmax = this.rmax, bmax = this.bmax, lmin = this.lmin, nodes = []
            , x = node.X, y = node.Y, t = y - 1, r = x + 1, b = y + 1, l = x - 1
            , _t = t > tmin && (map[t][x] === 0)
            , _r = r < rmax && (map[y][r] === 0)
            , _b = b < bmax && (map[b][x] === 0)
            , _l = l > lmin && (map[y][l] === 0), i = 0;
       
        if (_t) {
            nodes[i++] = [x, t];
            if (_l && (map[t][l] === 0)) nodes[i++] = [l, t];
            if (_r && (map[t][r] === 0)) nodes[i++] = [r, t];
        }
       
        if (_l) nodes[i++] = [l, y];
       
        if (_b) {
            nodes[i++] = [x, b];
            if (_l && (map[b][l] === 0)) nodes[i++] = [l, b]

当然可以!以下是一个用Python实现A*算法的示例代码: ```python import heapq class Node: def __init__(self, position, parent=None): self.position = position self.parent = parent self.g = 0 # Cost from start node to current node self.h = 0 # Heuristic cost from current node to goal node self.f = 0 # Total cost def __lt__(self, other): return self.f < other.f def astar(grid, start, goal): open_list = [] closed_list = set() start_node = Node(start) goal_node = Node(goal) heapq.heappush(open_list, start_node) while open_list: current_node = heapq.heappop(open_list) closed_list.add(current_node.position) if current_node.position == goal_node.position: path = [] while current_node.parent: path.append(current_node.position) current_node = current_node.parent path.append(start_node.position) return path[::-1] neighbors = get_neighbors(grid, current_node) for neighbor in neighbors: if neighbor.position in closed_list: continue cost = current_node.g + 1 if neighbor not in open_list or cost < neighbor.g: neighbor.g = cost neighbor.h = heuristic(neighbor, goal_node) neighbor.f = neighbor.g + neighbor.h neighbor.parent = current_node if neighbor not in open_list: heapq.heappush(open_list, neighbor) return None def get_neighbors(grid, node): neighbors = [] directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] # Up, down, left, right for dir in directions: new_position = (node.position[0] + dir[0], node.position[1] + dir[1]) if is_valid_position(grid, new_position): neighbors.append(Node(new_position, node)) return neighbors def is_valid_position(grid, position): rows = len(grid) cols = len(grid[0]) return 0 <= position[0] < rows and 0 <= position[1] < cols and grid[position[0]][position[1]] == 0 def heuristic(node, goal_node): return abs(node.position[0] - goal_node.position[0]) + abs(node.position[1] - goal_node.position[1]) # 测试示例 grid = [ [0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0] ] start = (0, 0) goal = (4, 4) path = astar(grid, start, goal) if path: print("Path found:") for position in path: print(position) else: print("No path found.") ``` 这是一个简单的实现,用于在给定的网格中找到起点和终点之间的最短路径。你可以根据自己的需求对代码进行修改和扩展。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值