淮安阿里云代理商:a*算法java源码

下面是使用 Java 实现 A* 算法的示例代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;

class Node implements Comparable<Node> {
    private int x;
    private int y;
    private int f; // f(n) = g(n) + h(n)
    private int g; // 到起点的实际代价
    private int h; // 到目标点的估计代价
    private Node parent;

    public Node(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getF() {
        return f;
    }

    public void setF(int f) {
        this.f = f;
    }

    public int getG() {
        return g;
    }

    public void setG(int g) {
        this.g = g;
    }

    public int getH() {
        return h;
    }

    public void setH(int h) {
        this.h = h;
    }

    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        this.parent = parent;
    }

    @Override
    public int compareTo(Node other) {
        return Integer.compare(this.f, other.f);
    }
}

public class AStarAlgorithm {
    private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    private int[][] grid;
    private int numRows;
    private int numCols;
    private Node startNode;
    private Node endNode;

    public AStarAlgorithm(int[][] grid) {
        this.grid = grid;
        this.numRows = grid.length;
        this.numCols = grid[0].length;
    }

    public List<Node> findPath(int startX, int startY, int endX, int endY) {
        startNode = new Node(startX, startY);
        endNode = new Node(endX, endY);

        PriorityQueue<Node> openSet = new PriorityQueue<>();
        Set<Node> closedSet = new HashSet<>();

        startNode.setG(0);
        startNode.setH(manhattanDistance(startNode, endNode));
        startNode.setF(startNode.getG() + startNode.getH());

        openSet.add(startNode);

        while (!openSet.isEmpty()) {
            Node currNode = openSet.poll();

            if (currNode.equals(endNode)) {
                return reconstructPath(currNode);
            }

            closedSet.add(currNode);

            for (int[] direction : DIRECTIONS) {
                int newX = currNode.getX() + direction[0];
                int newY = currNode.getY() + direction[1];

                if (isValid(newX, newY) && !closedSet.contains(new Node(newX, newY))) {
                    Node neighbor = new Node(newX, newY);

                    int tentativeG = currNode.getG() + 1;

                    if (!openSet.contains(neighbor) || tentativeG < neighbor.getG()) {
                        neighbor.setParent(currNode);
                        neighbor.setG(tentativeG);
                        neighbor.setH(manhattanDistance(neighbor, endNode));
                        neighbor.setF(neighbor.getG() + neighbor.getH());

                        if (!openSet.contains(neighbor)) {
                            openSet.add(neighbor);
                        }
                    }
                }
            }
        }

        return null;
    }

    private int manhattanDistance(Node node1, Node node2) {
        return Math.abs(node1.getX() - node2.getX()) + Math.abs(node1.getY() - node2.getY());
    }

    private boolean isValid(int x, int y) {
        return x >= 0 && x < numRows && y >= 0 && y < numCols && grid[x][y] != 1;
    }

    private List<Node> reconstructPath(Node node) {
        List<Node> path = new ArrayList<>();

        while (node != null) {
            path.add(node);
            node = node.getParent();
        }

        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args) {
        int[][] grid = {
            {0, 0, 0, 1, 0},
            {1, 1, 0, 1, 0},
            {0, 0, 0, 0, 0},
            {0, 1, 1, 1, 1},
            {0, 0, 0, 0, 0}
        };

        AStarAlgorithm astar = new AStarAlgorithm(grid);
        List<Node> path = astar.findPath(0, 0, 4, 4);

        if (path != null) {
            for (Node node : path) {
                System.out.println("(" + node.getX() + ", " + node.getY() + ")");
            }
        } else {
            System.out.println("No path found!");
        }
    }
}

这个示例代码使用 A* 算法实现了从起点到终点的路径搜索。在 findPath 方法中,使用优先队列 openSet 存储待探索的节点,使用集合 closedSet 存储已经探索过的节点。通过计算节点的 f(n) 值(f(n) = g(n) + h(n))来评估节点的优先级,优先探索具有较小 f(n) 值的节点。

注意:此示例代码中的 grid 是一个二维数组,其中 0 表示可以通过的路径,1 表示障碍物。将起点和终点的坐标传递给 findPath 方法,将返回路径上的所有节点。如果找不到路径,返回 null

请注意,这只是 A* 算法的一种实现方式,还有其他的实现方式可供选择。

淮安阿里云代理商:a*算法java源码

下面是一个使用A*算法的Java源码示例:

import java.util.*;

class Node implements Comparable<Node> {
    int x, y; // 节点的坐标
    int g, h; // g值为起点到当前节点的实际距离,h值为当前节点到终点的估计距离
    Node parent; // 父节点

    public Node(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int f() {
        return g + h;
    }

    @Override
    public int compareTo(Node o) {
        return Integer.compare(this.f(), o.f());
    }
}

class AStar {
    private int[][] grid;
    private int rows, cols;
    private Node startNode, endNode;

    public AStar(int[][] grid, int rows, int cols, int startX, int startY, int endX, int endY) {
        this.grid = grid;
        this.rows = rows;
        this.cols = cols;
        startNode = new Node(startX, startY);
        endNode = new Node(endX, endY);
    }

    public List<Node> findPath() {
        List<Node> openSet = new ArrayList<>();
        Set<Node> closedSet = new HashSet<>();
        openSet.add(startNode);

        while (!openSet.isEmpty()) {
            Node currentNode = openSet.get(0);

            // 寻找f值最小的节点
            for (int i = 1; i < openSet.size(); i++) {
                if (openSet.get(i).f() < currentNode.f()) {
                    currentNode = openSet.get(i);
                }
            }

            openSet.remove(currentNode);
            closedSet.add(currentNode);

            if (currentNode.x == endNode.x && currentNode.y == endNode.y) {
                return buildPath(currentNode);
            }

            List<Node> neighbors = getNeighbors(currentNode);

            for (Node neighbor : neighbors) {
                if (closedSet.contains(neighbor)) {
                    continue;
                }

                int newG = currentNode.g + 1;
                boolean isOpenSetContainsNeighbor = openSet.contains(neighbor);

                if (!isOpenSetContainsNeighbor || newG < neighbor.g) {
                    neighbor.g = newG;
                    neighbor.h = manhattanDistance(neighbor, endNode);
                    neighbor.parent = currentNode;

                    if (!isOpenSetContainsNeighbor) {
                        openSet.add(neighbor);
                    }
                }
            }
        }

        return null;
    }

    private int manhattanDistance(Node node1, Node node2) {
        return Math.abs(node1.x - node2.x) + Math.abs(node1.y - node2.y);
    }

    private boolean isValidPosition(int x, int y) {
        return x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] == 0;
    }

    private List<Node> getNeighbors(Node node) {
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};
        List<Node> neighbors = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            int newX = node.x + dx[i];
            int newY = node.y + dy[i];

            if (isValidPosition(newX, newY)) {
                neighbors.add(new Node(newX, newY));
            }
        }

        return neighbors;
    }

    private List<Node> buildPath(Node endNode) {
        List<Node> path = new ArrayList<>();
        Node currentNode = endNode;

        while (currentNode != null) {
            path.add(0, currentNode);
            currentNode = currentNode.parent;
        }

        return path;
    }
}

public class Main {
    public static void main(String[] args) {
        int rows = 5;
        int cols = 5;
        int[][] grid = {
            {0, 0, 0, 0, 0},
            {0, 1, 1, 1, 0},
            {0, 1, 0, 0, 0},
            {0, 1, 0, 1, 1},
            {0, 0, 0, 0, 0}
        };

        int startX = 0;
        int startY = 0;
        int endX = 4;
        int endY = 4;

        AStar aStar = new AStar(grid, rows, cols, startX, startY, endX, endY);
        List<Node> path = aStar.findPath();

        if (path != null) {
            for (Node node : path) {
                System.out.println("(" + node.x + ", " + node.y + ")");
            }
        } else {
            System.out.println("No path found.");
        }
    }
}

这个示例代码实现了一个迷宫路径查找的问题。grid数组表示迷宫地图,0表示可以通过的通路,1表示障碍物。startX和startY是起点的坐标,endX和endY是终点的坐标。程序会使用A*算法查找从起点到终点的最短路径,并将路径上的节点打印出来。如果没有找到路径,输出”No path found.”。

发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/118770.html

(0)
luotuoemo的头像luotuoemo
上一篇 2024年1月3日 04:24
下一篇 2024年1月3日 04:37

相关推荐

  • 三河阿里云代理商:阿里云云数据库RDS MySQL如何进行数据迁移和复制的稳定性?

    阿里云云数据库RDS MySQL的数据迁移和复制稳定性可以通过以下几个方面来保证: 高可用性架构:阿里云RDS提供了高可用性架构,数据在主实例上的写入会同步到备实例,实现了数据的自动同步和故障切换,保证了数据的稳定性和可靠性。 数据同步和复制技术:RDS MySQL使用了可靠的数据同步和复制技术,确保了数据在主备实例之间的同步和复制的稳定性。 数据迁移工具:…

    2023年11月14日
    19700
  • 烟台阿里云代理商:阿里巴巴网站需求分析

    阿里巴巴网站需求分析是指对于烟台阿里云代理商来说,分析阿里巴巴公司在建设自己的网站时所需要的功能和特性。 1.产品和服务展示:阿里巴巴是中国最大的B2B电子商务平台之一,其网站需要展示各类商品和服务的信息,包括图片、描述、价格、规格等。代理商需了解阿里巴巴的产品和服务范围,并提供相应的展示功能。 2.用户注册与登录:阿里巴巴网站需要提供用户注册和登录功能,用…

    2024年2月7日
    20400
  • 阿里云企业邮箱:如何利用企业邮箱防止信息泄露?

    阿里云企业邮箱:构建企业信息防泄露的坚固防线 在数字化时代,企业邮件作为核心通信工具承载着大量敏感信息。据IBM调研显示,2022年企业平均数据泄露成本高达435万美元,其中邮件泄露占比超60%。阿里云企业邮箱凭借其领先的安全架构和智能化防护体系,为企业打造了全方位的信息防泄露解决方案。 一、多层加密体系:筑牢数据传输壁垒 1. 端到端传输加密 采用国际标准…

    2025年6月23日
    3500
  • 腾讯云的短信服务

    腾讯云提供了短信服务,用于向用户发送短信通知、验证码等信息。腾讯云短信服务具有高可靠性、高效性和全面的覆盖,可以支持在全球范围内发送短信。通过腾讯云短信服务,用户可以进行手机号码验证、营销推广、用户通知等功能。 腾讯云短信服务的主要特点包括: 全球覆盖:支持向全球200多个国家和地区发送短信。 高效可靠:采用腾讯自研的海量短信并发能力,确保短信即时送达。 防…

    2023年9月11日
    20000
  • 唐山阿里云代理商:asp.net 数据库访问数据库

    在ASP.NET中访问数据库通常是通过ADO.NET来实现的,ADO.NET提供了一系列类和方法,可以方便地与数据库交互。以下是一些常见的步骤: 连接到数据库:首先需要创建一个数据库连接对象,指定数据库的连接字符串,然后调用Open方法打开连接。 string connectionString = "Data Source=myServerAddr…

    2024年2月23日
    21200

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

4000-747-360

在线咨询: QQ交谈

邮件:ixuntao@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
购买阿里云服务器请访问:https://www.4526.cn/