Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在二维阵列上实现星型算法_Java_Arrays_Algorithm - Fatal编程技术网

Java 在二维阵列上实现星型算法

Java 在二维阵列上实现星型算法,java,arrays,algorithm,Java,Arrays,Algorithm,我被要求用AI为一个项目编写一个蛇游戏。我在编码50x50 2d阵列上实现的最短路径算法时遇到问题。我已经为AStar寻路算法编写了代码(见下面的代码),但它似乎不起作用。有人能帮我纠正我的代码吗?还有人能帮我编码Dijktra的算法吗?因为我正在努力为2d数组编码。值得一提的是,最短路径算法是让我的snake找到最短路径以到达2d板上的苹果。希望有人能帮忙。 让我的问题更清楚一点:我的问题是我需要找到2d数组上两点之间的最短路径,因为我是一名编码初学者,我需要帮助编写一个算法,以找到起点和终点

我被要求用AI为一个项目编写一个蛇游戏。我在编码50x50 2d阵列上实现的最短路径算法时遇到问题。我已经为AStar寻路算法编写了代码(见下面的代码),但它似乎不起作用。有人能帮我纠正我的代码吗?还有人能帮我编码Dijktra的算法吗?因为我正在努力为2d数组编码。值得一提的是,最短路径算法是让我的snake找到最短路径以到达2d板上的苹果。希望有人能帮忙。 让我的问题更清楚一点:我的问题是我需要找到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));
}
//实现*
公共距离(点电流、点目标){
返回Math.abs(current.getX()-goal.getX())+Math.abs(current.getY()-goal.getY());
}
公共阵列列表aStar(Point myHead,Point apple){
ArrayList closedSer=新建ArrayList();
ArrayList openSet=新的ArrayList();
openSet.add(myHead);
ArrayList cameFrom=新建ArrayList();
int[]gscore=新int[50][50];

对于(int i=0;i,这里是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);
    }
}
//Dijkstra的单源最短路径算法的Java程序。
//该程序用于图形的邻接矩阵表示。
类最短路径
{
/*用于查找具有最小距离值的顶点的实用函数,
从尚未包含在最短路径树中的顶点集*/
静态最终INTV=9;
int minDistance(int dist[],boolean sptSet[]
{
//初始化最小值
int min=Integer.MAX\u值,min\u索引=-1;
对于(int v=0;vif(sptSet[v]==false&&dist[v]这是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);
    }
}
//Dijkstra的单源最短路径算法的Java程序。
//该程序用于图形的邻接矩阵表示。
类最短路径
{
/*用于查找具有最小距离值的顶点的实用函数,
从尚未包含在最短路径树中的顶点集*/
静态最终INTV=9;
int minDistance(int dist[],boolean sptSet[]
{
//初始化最小值
int min=Integer.MAX\u值,min\u索引=-1;
对于(int v=0;v如果(sptSet[v]==false&&dist[v]你应该在每个符号前后留出一个空格(
+-=/*…
)有什么问题?你需要让你的问题更清楚,才能得到一个好的答案。提供一个清楚的问题,你的答案会对你更有帮助。这里可能有重复的东西可以比较(但在C++中)你应该在每个符号前后留出一个空格(
+-=/*…
)问题是什么?为了得到一个好的答案,你需要让你的问题更清楚。提供一个清晰的问题,你的答案将对你更有帮助。这里可能有重复的东西可以比较(但在C++中)非常感谢您的帮助。在您的实现中,我只不了解两件事。第一件事是dijkstra函数的第二个参数,我知道您已经在上面解释过了,但它是否表示我在图[I][j]中开始的节点?第二件事是内部for循环(在dijkstra函数中),是否要获取当前单元格的所有邻居并将其添加到dist[v]?感谢您的帮助第二个参数表示源节点,我们将从中找出所有其他节点的距离。假设我有节点(1、2、3、4、5)我想找出从节点1到2,3,4,5的距离。然后1是源节点。V代表节点数。对于你的情况,它将是50。我的代码中有一个小错误,现在它被更正了。谢谢你指出它!非常感谢你的帮助。我只是不理解你实现中的两件事。第一件是dijkstra函数的第二个参数,我知道你已经在上面解释过了,但它是否代表我在图[I][j]中开始的节点?第二个是内部for循环(在dijkstra函数中),我是否应该得到当前单元格的所有邻居并将它们添加到dist[v]?感谢您的帮助第二个参数表示源节点,我们将从中找出所有其他节点的距离。假设我有节点(1、2、3、4、5)我想找出从节点1到2,3,4,5的距离。然后1是源节点。V代表节点数。对于你的情况,它将是50。我的代码中有一个小错误,现在它被更正了。谢谢你指出!