【问题标题】:Java Maze shortest path 2d int arrayJava Maze 最短路径 2d int 数组
【发布时间】:2012-01-16 03:28:14
【问题描述】:

我目前正忙于一个项目。 我的目标是使用 Dijkstra 算法。

我知道我从点 (0,0) 开始我查看起点旁边的两个节点,然后我首先移动到最小的节点并查看周围的节点。我的迷宫是随机的,但为了便于开始,让我们说以下是我的迷宫。

我将从 (0,0) 开始并希望在 (9,9) 结束,数字是危险级别,我们的目标是最安全的路径,而不是最短的路径。

我需要推动以了解如何进行设置。 我知道我需要一个列表或路径来保持我的位置和我想要查看的位置。但我不知道如何在 java 中做到这一点。

import java.awt.Point;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class solver {

    /**
     * @param args
     */
    public static int[][]maze;
    public static int[][]openlist;
    public static int[][]closed;
    public static int[][]copy;
    public static int danger;
    public static int size=100;
    static int Max=9;
    static int Min=0;
    public static List path = new ArrayList();
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        maze = new int[size][size];
        openlist = new int[size][size];
        closed = new int[size][size];
        copy = new int[size][size];
        filler(maze);
        copy=dijstkra();
        printer(maze);
        //printer(copy);
        EDSfAO(maze,0,0);
        printer(openlist);
        printer(copy);
    }
    private static Boolean notwall(int i, int j){

        if((i>maze.length-1)||(j>maze.length-1)||(i<0)||(j<0))
        {return false;}

        return true;}
    private static int[][] dijstkra(){


        for(int i=0;i<maze.length;i++){
            for(int j=0;j<maze.length;j++){
                copy[i][j]=100000000;
            }}
        copy[0][0]=0;
        return copy;
        }

    private static void EDSfAO(int[][] maze,int i,int j){
        int min=100000000;
        int holdx = 0;  
        int holdy = 0;
        openlist[i][j]=1;
        danger=copy[i][j];
        if(i==maze.length-1&&j==maze.length-1){

            printer(copy);
            for(holdx=0;holdx<path.size();holdx++){

                System.out.print(path.get(holdx));

            }


        }
        else{
        if(notwall(i+1,j)&&openlist[i+1][j]!=1){
            copy[i+1][j]=danger+maze[i+1][j];
        } if(notwall(i,j+1)&&openlist[i][j+1]!=1){
            copy[i][j+1]=danger+maze[i][j+1];
        } if(notwall(i,j-1)&&openlist[i][j-1]!=1){
            copy[i][j-1]=danger+maze[i][j-1];
        } if(notwall(i-1,j)&&openlist[i-1][j]!=1){
            copy[i-1][j]=danger+maze[i-1][j];
        }
        for(int x=0;x<maze.length;x++){
            for(int y=0;y<maze.length;y++){

            if(openlist[x][y]!=1){

                if(min>copy[x][y]){
                min=copy[x][y];
                holdx=x;    
                holdy=y;
                }

            }


        }}
        moveToPosition(holdx,holdy);
        }
    }


    private static void moveToPosition(int x, int y) {

            openlist[x][y]=1;
            path.add("("+x+","+y+")");
            openlist[x][y]=1;
            EDSfAO(maze,x,y);
    }

private static void printer(int[][] maze) {
        // TODO Auto-generated method stub
    for(int i=0;i<maze.length;i++){
        for(int j=0;j<maze.length;j++){
        System.out.print("["+maze[i][j]+"]");                       
        }
        System.out.println();
        }

    }

public static void filler(int[][] maze){

        for(int i=0;i<maze.length;i++){

            for(int j=0;j<maze.length;j++){
            //If i=0 AND j=0 then maze[0][0]= 0(start) OR i= maze.length-1 AND j= maze.length-1 then maze[maze.length][maze.length]=0
            if((i==0 && j==0) || (i==maze.length-1 && j==maze.length-1)){

                maze[i][j]=0;   

            }else{
                maze[i][j]=Min + (int)(Math.random() * ((Max - Min) + 1));
            }
            }
            }
    }
}

迷宫没有墙壁连接,所有的盒子都是房间。 我一直在努力解决这个问题,我真的可以使用推力。 我看了很多关于 dijstkra 算法的视频,我现在真的迷路了。

我添加了一个数组,我通过将节点设为 100000000 开始,但起始节点 (0,0) 为 0。

有人可以帮我完成接下来的步骤吗?我知道这是家庭作业,但我的时间不多了,真的需要一些指示。

更新:

好的,所以我让它工作正常。它会打印它所采用的路径,但如果它找到更好的路径,它会打印两者,有人可以帮我解决这个问题。

如果我做 100X100 元素,它也会中断,有人能告诉我为什么吗? 这是最后一个真正的“编程作业”。正如您所料,这将涉及图表(带有扭曲);但当然,也会涉及到一些问题的解决。 说明


想象一个“地牢游戏”,其中所有房间都布置在一个完美的网格中,在一个方形的环境中。每个房间都有一个生物构成某种程度的危险,从 0(无害)到 9(避免是谨慎的)。目标是找到一条从头到尾穿过地牢的路径,以最大限度地减少总体危险。

每个房间,除非在边界处,只存在于上、下、左、右方向(无对角线)。入口在左上角(0,0),出口在右下角(n-1,n-1)。

列出所有必须遍历的“房间”,以房间坐标路径的形式,从开始到结束。

例如:

(0,0) (1,0) (2,0) (2,1) (2,2) (2,3) (3,3) (4,3) (4,4)

总危险 = 11 输入

输入文件将包含 100 行,每行 100 位,0-9。 (是的,10,000 间是很多房间,但幸运的是,我们勇敢的旅行者每次出门时都不会没有便携式计算机和去年节日礼物交换中收到的适用于所有场合的电子数据集的集合;它可能被重新赠送了。 )*

*对于此作业,您必须生成自己的测试数据。这就是为什么我不去参加这些聚会的原因... 输出

程序应将输出写入文件(采用上述格式,包括“total danger”输出)。 谢谢。

UPDATE2:我发现我的编码有错误

if(min>copy[x][y]){
                min=copy[x][y];
                holdx=x;    
                holdy=y;
                }

这将使它测试给定点的每条路径我的最短路径大于另一条路径我该如何解决这个问题?

我错过了什么? 更新我完成了这个感谢非常小的帮助。

【问题讨论】:

    标签: java nodes dijkstra


    【解决方案1】:

    您的解决方案可以基于 Cormen、Leiserson、Rivest 和 Stein 的“算法简介”第 2 版中的算法。在第 24 章中,他们分析了“单源最短路径”算法,在 24.3 中你有 Dijkstra。

    我将在这里使用伪代码。您可以将下面的最小优先级队列替换为另一种数据结构,例如 Java 中的地图。它不会很快,但它会起作用,这可能是一个令人满意的第一次尝试。如果你愿意,我还有一个最低优先级队列的 Java 实现。

    假设您有一个由二维数组表示的迷宫,如代码中所示:int[M][N] 迷宫。第一个索引是行索引,第二个是列索引,从零开始。因此,行从 0 到 M-1,列从 0 到 N-1。值 maze[row][column] 表示与 (row, column) 处的房间相关的危险。我们需要一个方便的表示来获得迷宫中两个房间之间的权重,并知道哪些房间与特定房间相邻。

    这个想法是将数组展平并将每一行并排放置:row1,row2,...,rowM。然后我们可以给每个房间一个索引 i。为了能够使用这个想法,我们需要在不同类型的坐标之间进行转换:(row, column) -> i 和 i -> (row, column)。

    convert_to_index(row, column) ::= row * N + column
    convert_to_pair(i) ::= (i div N, i modulo N)
    

    假设 SIZE 为 M*N,即迷宫中的房间总数。

    现在我们可以用危险值制作一个表示迷宫的邻接矩阵:int[SIZE][SIZE] adjacency_matrix,第一个索引是FROM,第二个是TO。在一个牢房中,我们发现从一个房间到另一个房间的成本或重量。请注意,给定一个特定房间,只有几个房间与该房间相邻。从那个房间无法到达迷宫中的其他房间。按照惯例,我们将使用最大的整数来表示,并使用常量 INFINITY。其他值表示危险,范围从 0 到 9。矩阵将是稀疏的,并且有一些技术可以优化它。

    当我们有一个位于 (r, c) 的房间时,与它相邻的房间是什么?我们希望在我们的算法中直接使用一个索引向量。如果我们不考虑迷宫边界,我们有:(r-1, c-1), (r-1, c), (r-1, c+1), (r, c-1) , (r, c+1), (r+1, c-1), (r+1, c) 和 (r+1,c+1)。然后我们可以对它们中的每一个应用 convert_to_index,检查它们是否在 0..SIZE-1 范围内,并用它来初始化矩阵。因此,例如,从 (r, c) 到 (r-1, c-1) 具有迷宫 [r-1, c-1] 和从 (r-1, c-1) 到(r, c) 的成本为 maze[r, c]。但是从 (r, c) 到另一个遥远的房间的成本是 10,这是不可达的,反之亦然。

    adjacent_rooms(r, c) ::=
        Given the vector [(r-1, c-1), (r-1, c), (r-1, c+1), (r, c-1), (r, c+1), (r+1, c-1), (r+1, c), (r+1,c+1)]
        Filter it by deleting pairs whose row is not in 0..M-1 or whose column is not in 0..N-1
        Then apply the function convert_to_index to each resulting pair (map operation)
        Return the result
    
    for i in 0..SIZE-1 loop
        for j in 0..SIZE-1 loop
            adjacency_matrix[i, j] := -1
        end loop
    end loop
    
    for i in 0..SIZE-1 loop
        (current_r, current_c) := convert_to_pair(i)
        adjacent_room_indexes := adjacent_rooms(current_r, current_c)
        for j in 0..SIZE-1 loop
            if adjacency_matrix[i, j] == -1 then
                (r, c) := convert_to_pair(j)
                if i == j then adjacency_matrix[i, j] := 0
                elsif j in adjacent_room_indexes then adjacency_matrix[i, j] := maze[r, c]; adjacency_matrix[j, i] := maze[current_r, current_c]
                else adjacency_matrix[i, j] := INFINITY
            end if
        end loop
    end loop
    

    接下来,我们需要一个最短路径估计的向量估计(参见第 585 页)和一个先行向量(参见第 584 页)。

    for i in 0..SIZE-1 loop
        predecessors[i] := NONE
        estimates[i] := INFINITY
    end loop
    

    从起点到起点的成本为 0。

    estimates[0] := 0
    

    初始化属于 MST(最小生成树)的顶点集

    mst := empty set
    

    最小优先级队列 q 被初始化

    for i in 0..SIZE-1 loop
        q.add(i, estimates[i])
    end loop
    
    until q.empty? loop
        u, u_d = q.delete_min
        mst.add(u)
        (current_r, current_c) := convert_to_pair(i)
        adjacent_room_indexes := adjacent_rooms(current_r, current_c)
        for i in 0..adjacent_room_indexes.length-1 loop
            v := adjacent_room_indexes[i]
            cost = adjacency_matrix[u, v]
            if cost < q[v]
              predecessors[v] = u
              estimates[v] = c
              q[v] = c
            end
        end loop
    end loop
    

    任务完成。我们的路径在predecessors,成本在estimates。

    这可能有点矫枉过正,A* 可能会更好。但我猜想使用 Dijkstra 是你功课的要求。如果你想探索A*,我建议你看看A* Pathfinding for Beginners和Amit’s A* Pages。

    【讨论】:

    • "如果你愿意,我也有一个最低优先级队列的 Java 实现。"可以分享一下吗?
    • 是的,当然,两周后我休假回来。
    • 这里是 pastebin:pastebin.com/4vBUB7pc。请注意,它使用堆数据结构来提供所需的属性。代码没有注释,因此可能不容易理解。
    • 不客气。我有一篇法语的关于堆排序的详细文章,我打算用它写一篇关于堆数据结构的博客文章,然后再写一篇关于优先级队列实现的文章(英文)。可能需要几周时间才能完成,但我已经有了服务器来托管博客。完成后我会回到这里并编辑答案。
    【解决方案2】:

    我继续执行 ccoakley 提到的算法。在下面找到部分代码以帮助您朝着正确的方向前进:

    import java.util.HashSet;
    import java.util.Set;
    
    // 1. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.
    // 2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes except the initial node.
    // 3. For the current node, consider all of its unvisited neighbors and calculate their tentative distances. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B (through A) will be 6+2=8. If this distance is less than the previously recorded distance, then overwrite that distance. Even though a neighbor has been examined, it is not marked as visited at this time, and it remains in the unvisited set.
    // 4. When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again; its distance recorded now is final and minimal.
    // 5. If the unvisited set is empty, then stop. The algorithm has finished.
    // 6. Set the unvisited node marked with the smallest tentative distance as the next "current node" and go back to step 3.
    public class Dijkstra {
    
        class Node {
            String name;
            Integer distance = Integer.MAX_VALUE;
            boolean visited;
            Set<Edge> edges = new HashSet<Edge>();
    
            Node(String name) {
                this.name = name;
            }
    
            Edge connect(Node destination, int length) {
                Edge edge = new Edge();
                edge.length = length;
                edge.from = this;
                edge.to = destination;
                edges.add(edge);
                destination.edges.add(edge);
                return edge;
            }
    
            @Override
            public String toString() {
                return name;
            }
        }
    
        class Edge {
            int length;
            Node from;
            Node to;
    
            Node getNeighbor(Node origin) {
                if (from == origin) {
                    return to;
                }
                else if (to == origin) {
                    return from;
                }
                else {
                    throw new IllegalArgumentException("This edge is not connected to node " + origin);
                }
    
            }
    
            @Override
            public String toString() {
                return String.format("%s-%s", from, to);
            }
        }
    
        /**
         * <pre>
         * a - b - c
         * |   |   
         * d - e   |
         * |
         * f - g - h
         * </pre>
         * 
         * @return
         */
        private Set<Node> initialize() {
            Node a = new Node("a");
            Node b = new Node("b");
            Node c = new Node("c");
            Node d = new Node("d");
            Node e = new Node("e");
            Node f = new Node("f");
            Node g = new Node("g");
            Node h = new Node("h");
    
            a.connect(b, 4);
            a.connect(d, 8);
            b.connect(c, 6);
            b.connect(e, 1);
            c.connect(h, 7);
            d.connect(e, 2);
            d.connect(f, 5);
            f.connect(g, 3);
            g.connect(h, 1);
    
            a.distance = 0;
    
            Set<Node> unvisited = new HashSet<Dijkstra.Node>();
            unvisited.add(a);
            unvisited.add(b);
            unvisited.add(c);
            unvisited.add(d);
            unvisited.add(e);
            unvisited.add(f);
            unvisited.add(g);
            unvisited.add(h);
    
            return unvisited;
        }
    
        private Set<Node> solve(Set<Node> unvisited) {
    
            Set<Node> visited = new HashSet<Node>();
    
            while (!unvisited.isEmpty()) {
    
                System.out.println(String.format("Unvisited nodes:%s", unvisited.size()));
                print(unvisited);
                Node current = findNodeWithSmallestDistance(unvisited);
                System.out.println(String.format("Current node:%s", current));
                updateNeighbors(current);
                current.visited = true;
                unvisited.remove(current);
                visited.add(current);
            }
    
            return visited;
        }   
    
        private void updateNeighbors(Node current) {
    
            for (Edge edge : current.edges) {    
                Node neighbor = edge.getNeighbor(current);
                if (!neighbor.visited) {
                    int tentativeNeighborDistance = current.distance + edge.length;
                    if (tentativeNeighborDistance < neighbor.distance) {
                        neighbor.distance = tentativeNeighborDistance;
                        System.out.println(String.format("Neighbor:%s distance:%s", neighbor, neighbor.distance));
                    }
                    else {
                        System.out.println(String.format("Neighbor:%s no shorter path     found", neighbor));
                    }
                }
                else {
                    System.out.println(String.format("Neighbor:%s already visited",     neighbor));
                }
            }
        }
    
        private Node findNodeWithSmallestDistance(Set<Node> nodes) {
            Node smallest = null;
            for (Node node : nodes) {
                if (smallest == null || node.distance < smallest.distance) {
                    smallest = node;
                }
            }
            return smallest;
        }
    
        private void print(Set<Node> visited) {
            for (Node node : visited) {
                System.out.println(String.format("Node:%s has distance:%s", node, node.distance));
            }
        }
    
        public static void main(String[] args) {
            Dijkstra edsger = new Dijkstra();
            Set<Node> unvisited = edsger.initialize();
            Set<Node> visited = edsger.solve(unvisited);
            edsger.print(visited);
        }
    }
    

    编辑:添加缺失的位

    【讨论】:

      【解决方案3】:

      我刚刚查看了Dijkstra's Algorithm 上的维基百科文章。

      1. 为每个节点分配一个暂定距离值:将初始节点设置为零,将所有其他节点设置为无穷大。
      2. 标记所有未访问的节点。将初始节点设置为当前节点。创建一组未访问节点,称为未访问集 由除初始节点之外的所有节点组成。
      3. 对于当前节点,考虑其所有未访问的邻居并计算它们的暂定距离。例如,如果当前 节点 A 用距离 6 标记,连接它的边 邻居 B 的长度为 2,那么到 B(通过 A)的距离将是 6+2=8。如果这个距离小于之前记录的距离, 然后覆盖那个距离。虽然邻居已经 已检查,此时未将其标记为已访问,并且仍保留在 未访问的集合。
      4. 当我们考虑完当前节点的所有邻居后,将当前节点标记为已访问并将其从 未访问集。被访问的节点将永远不会被再次检查;它的 现在记录的距离是最终的和最小的。
      5. 如果未访问集为空,则停止。算法已完成。
      6. 将标记为最小暂定距离的未访问节点设置为下一个“当前节点”并返回步骤3。

      一开始只是天真地接近它。哎呀,把它当作“程序员的阅读理解”。在这种情况下,诀窍是将二维数组映射到一组图形节点。每个节点都需要“一个暂定的距离值”。好的,您的节点由它们的 i,j 值定义。做一些事情,这样你就可以在给定 i 和 j 的情况下获取/设置一个 tentative_distance_value。

      你需要标记一个节点是否被访问。同样的想法。

      您需要一个“当前节点”。相同的想法,但更简单。

      我知道我需要一个列表或路径来保存它们。我现在和曾经想要 看。但我不知道如何在 java 中做到这一点。

      从技术上讲,您不需要维护运行算法的路径。如果你不这样做,你将不得不弄清楚如何从算法的结果中构造它,但这当然是可能的。

      【讨论】:

      • 我也不知道如何构建它。你能帮我根据结果构建它吗?
      • 从迷宫的尽头开始,tentative_distance_value 标签代表到原点的最短距离。您可以通过贪婪地添加带有标签的节点以及从该空间移动到您的空间的成本来构建路径。由于空间的成本与您的问题的边缘无关(这是空间的危险,而不是您输入的特定方向),您可以只使用标签。
      • 在我找到到达终点的成本之后,你就对了。我只是添加了隔壁的小型房间并继续前进,直到达到 (0,0)。谢谢
      【解决方案4】:

      一旦您了解了如何使用 Dijkstra 算法,您就可以使用 ArrayList,其中包含表示您之前位置的数字对:

      List<Point> path = new ArrayList<Point>();
      

      然后您可以编写一个 Point 类,该类简单地包装两个 int 原语,x 和 y。

      所以当你移动时,你可以使用:

      private void moveToPosition(int x, int y) {
          path.add(new Point(x, y));
      
          // Move yourself to this point
          ...
      }
      

      至于学习如何真正使用算法,我认为这在某种程度上是你功课的重点,我们不想破坏你的乐趣!

      关于算法的 Wikipedia 文章相当有用,但我感觉你的课堂笔记也会有所帮助。

      Dijkstra's algorithm on Wikipedia

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多