淮安阿里云代理商: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

相关推荐

  • 嘉峪关阿里云企业邮箱代理商:如何登录阿里云服务器

    如何登录阿里云服务器 作为嘉峪关阿里云企业邮箱代理商,我们深知企业邮箱在日常工作中的重要性。而使用阿里云企业邮箱后,不仅可以提高团队协作效率,还能享受到更多安全、稳定、便捷的服务。 登录阿里云服务器是每个企业用户都需要了解和掌握的操作之一。下面我们将简要介绍如何登录阿里云服务器: 通过SSH登录 SSH是Secure Shell的缩写,它是一种加密的网络传输…

    2024年2月26日
    13800
  • 阿里云国际站代理商:阿里云 二维码生成

    阿里云国际站没有明确的二维码生成服务,但是提供了丰富的开放API,用于开发公共服务和私有云服务。你可以使用这些API来开发自己的二维码生成服务。 而阿里云在国内站确实提供了一个名为”阿里云盾”的服务,内含二维码生成服务, 进入阿里云官网,登录你的阿里云账户。 在控制台中点击选择“安全服务”,然后点击“阿里云盾”。 在阿里云盾的页面中,…

    2024年3月19日
    16100
  • 库尔勒阿里云企业邮箱代理商:阿里云域名怎么看备案号

    库尔勒阿里云企业邮箱代理商:阿里云域名怎么看备案号 阿里云作为国内互联网领军企业,其托管的域名备案对于网站运营至关重要。在进行网站备案时,一定要注意域名备案情况,否则容易受到惩罚。 如何查看阿里云域名备案号 若您的网站托管在阿里云上,有以下两种方式可查询备案号: 登录阿里云账号,在“域名列表”页面选择需要查询的域名,然后点击“备案信息”即可看到备案号。 通过…

    2024年3月14日
    15100
  • 温州阿里云代理商:access数据库微课

    阿里云代理商:Access数据库微课 随着互联网的快速发展,数据处理和存储需求不断增长。在企业管理和运营中,数据库成为了必不可少的工具。作为温州地区的阿里云代理商,我们将为您介绍阿里云数据库的优势。 1. 强大的性能和可靠性 阿里云数据库采用分布式架构,具备高可靠性和稳定性。它通过数据备份、数据复制和容灾机制来保障数据库的可用性。无论是在高负载还是突发流量的…

    2024年1月23日
    14600
  • 衡东阿里云企业邮箱代理商:阿里邮箱如何分配账号

    衡东阿里云企业邮箱代理商:阿里邮箱账号分配 一、阿里云企业邮箱的优势 阿里云企业邮箱作为一款专业的企业级邮件解决方案,具有以下优势: 安全可靠:阿里云的强大安全系统保障企业邮件的安全性和稳定性。 高效便捷:支持大容量附件传输,提供邮件搜索和过滤功能,帮助用户快速查找和管理邮件。 多平台适配:支持PC端、移动端等多种终端,用户可以随时随地进行邮件收发和管理。 …

    2024年1月28日
    17100

发表回复

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

联系我们

4000-747-360

在线咨询: QQ交谈

邮件:ixuntao@qq.com

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

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