gpt4 book ai didi

java - 在二维数组上实现 A Star 算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:17:07 25 4
gpt4 key购买 nike

我需要为一个项目编写一个带有 AI 的贪吃蛇游戏。我在编写在 50x50 二维数组上实现的最短路径算法时遇到问题。我已经为 AStar 寻路算法编写了代码(请参阅下面的代码),但它似乎不起作用。有人可以帮我更正我的代码,也有人可以帮我编写 Dijktra 算法的代码,因为我正在努力为二维数组编写代码。值得一提的是,最短路径算法是让我的蛇在2d板上找到到达苹果的最短路径。希望有人能帮忙。只是为了让我的问题更清楚:我的问题是我需要找到二维数组上两点之间的最短路径,因为我是编码初学者我需要帮助编写算法以找到初始点之间的最短路径和终点,例如 Dijktra 或 AStar。

        //implementing a*
public int manhattenDistance(Point current, Point goal){
return Math.abs(current.getX()-goal.getX())+Math.abs(current.getY()-goal.getY());
}
public ArrayList<Point> aStar(Point myHead, Point apple){
ArrayList<Point> closedSer=new ArrayList<>();
ArrayList<Point> openSet=new ArrayList<>();
openSet.add(myHead);
ArrayList<Point> cameFrom=new ArrayList<>();

int[][] gscore=new int[50][50];
for(int i=0;i<gscore.length;i++){
for(int j=0;j<gscore.length;j++)
gscore[i][j]=Integer.MAX_VALUE;
}
gscore[myHead.getX()][myHead.getY()]=0;

int[][] fscore=new int[50][50];
for(int i=0;i<fscore.length;i++){
for(int j=0;j<fscore.length;j++)
fscore[i][j]=Integer.MAX_VALUE;
}
fscore[myHead.getX()][myHead.getY()]=manhattenDistance(myHead,apple);

while(!openSet.isEmpty()){
Point current; int[] fscores=new int[openSet.size()];
for (int i=0;i<openSet.size();i++){
Point p=openSet.get(i);
fscores[i]=manhattenDistance(p,apple);
}int min=fscores[0], index=openSet.size();
for(int i=0;i<fscores.length-1;i++){
if(fscores[i]<fscores[i+1]) {
min = fscores[i];
index = i;
}if(fscores[i+1]<min){
min=fscores[i+1]; index=i+1;
}
}
current=openSet.get(index-1);
if(current==apple) return cameFrom;//.toArray(new Point[cameFrom.size()]);// reconstructpath(cameFrom,current);
openSet.remove(index-1);
closedSer.add(current);

Point[] currentNeighbourstemp=current.getNeighbours();
ArrayList<Point> currentNeighbours=new ArrayList<>();
for(Point n:currentNeighbourstemp)
if(isOnBoard(n)) currentNeighbours.add(n);
/*for(int i=0;i<currentNeighbours.length;i++){
for(int j=0; j<openSet.size();j++)
if(currentNeighbours[i]==openSet.get(j)) continue;;
}*/

for (Point neighbour:currentNeighbours){
Double tentative_gscore=gscore[neighbour.getX()][neighbour.getY()]+distanceBetween(neighbour,current);
boolean in=false;
for(int i=0;i<openSet.size();i++){//checking if in oppenset
if(neighbour==openSet.get(i)) in=true;
}
if(!in) openSet.add(neighbour);
else if(tentative_gscore>=gscore[neighbour.getX()][neighbour.getY()]) continue;
gscore[neighbour.getX()][neighbour.getY()]=tentative_gscore.intValue();
fscore[neighbour.getX()][neighbour.getY()]=gscore[neighbour.getX()][neighbour.getY()]+manhattenDistance(neighbour,apple);
}
}
return cameFrom;//.toArray(new Point[cameFrom.size()]);
}

public Double distanceBetween(Point a,Point b){
return Math.sqrt((b.getX()-a.getX())*(b.getX()-a.getX())+(b.getY()-a.getY())*(b.getY()-a.getY()));
}
public static float invSqrt(float x) {
float xhalf=0.5f*x;
int i=Float.floatToIntBits(x);
i=0x5f3759df-(i>>1);
x=Float.intBitsToFloat(i);
x=x*(1.5f-xhalf*x*x);
return x;
}
public float gravityDistance(Point that,Point th){
if(this.equals(that)) return Float.MAX_VALUE;
return 20.0f*invSqrt(Math.abs(th.x-that.x)+Math.abs(th.y-that.y));
}

最佳答案

这是 Dijkstra 最短路径算法的 JAVA 实现:

// A Java program for Dijkstra's single source shortest path algorithm.
// The program is for adjacency matrix representation of the graph.

class ShortestPath
{
/* A utility function to find the vertex with minimum distance value,
from the set of vertexes not yet included in shortest path tree */
static final int V = 9;
int minDistance(int dist[], boolean sptSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;

for(int v = 0; v < V; v++)
{
if(sptSet[v] == false && dist[v] <= min)
{
min = dist[v];
min_index = v;
}
}
return min_index;
}

// A utility function to print the constructed distance array
void printSolution(int dist[], int n)
{
System.out.println("Vertex Distance from Source");
for(int i = 0; i < V; i++)
System.out.println(i+" \t\t "+dist[i]);
}

/* Function that implements Dijkstra's single source shortest path
algorithm for a graph represented using adjacency matrix
representation */
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V]; /* The output array, dist[i] will hold
the shortest distance from src to i */
/* sptSet[i] will be true if vertex i is included in shortest
path tree or shortest distance from src to i is finalized */
Boolean sptSet[] = new Boolean[V];

for(int i = 0; i < V; i++)
{
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}

// Distance of source vertex from itself is always 0
dist[src] = 0;

//Find shortest path for all vertexes
for(int count = 0; count < V-1; count++)
{
/* Pick the minimum distance vertex from the set of vertexes
not yet processed. u is always equal to src in first
iteration. */
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed
sptSet[u] = true;

/* Update dist value of the adjacent vertexes of the
picked vertex. */
for(int v = 0; v < V; v++)
{
/* Update dist[v] only if it is not in sptSet, there is an
edge from u to v, and total weight of path from src to
v through u is smaller than current value of dist[v] */
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u]+graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
}

// print the constructed distance array
printSolution(dist, V);
}
public static void main(String[] args)
{
// Create an example graph
int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
ShortestPath t = new ShortestPath();
t.dijkstra(graph, 0);
}
}

代码很容易解释。需要注意的几点:

  • 这里我采用了一个 9X9 二维数组。 9 行代表图中的 9 个节点。每列代表其他节点与相应节点之间的连接。
  • graph[i][j]位置的非零值表示ij之间存在联系。该值表示从 ij 的成本。
  • graph[i][j] 位置中的零表示 ij 没有连接。
  • src 表示将计算到所有其他点的距离的源。
  • 请记住,您的网格代表一个图形,其中顶点/节点是单元格,边是相邻单元格。

希望对您有所帮助!如果您在理解算法时遇到任何问题,请告诉我。祝你好运!

关于java - 在二维数组上实现 A Star 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39774417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com