java - 如何将网格中单元格的邻居存储到优先级队列中

标签 java algorithm data-structures priority-queue dijkstra

假设我有一个 4 x 4 网格,即 16 个单元格。每个单元格包含 1,5 之间的值。例如。

     0 1 2 3
     _ _ _ _
0 - |2|1|3|2|
1 - |1|3|5|1|
2 - |5|2|1|4|
3 - |2|4|2|1|

现在我知道我需要使用 Dijkstra 算法。另外,为了优化这一点,我需要使用优先级队列。

我的目标是找到每个单元格到目的地的最短总和。源在网格上可以是随机的,目的地也可以是随机的。 (即并不总是从左上到右下)。

我曾经处理过使用相邻矩阵的图表。然而,对于这个网格,创建一个相邻矩阵是否明智?即,将所有不相邻的字段设置为无穷大。将单元插入优先级队列的最充分的方法是什么?会是{(行,列),距离}吗?

只是为了澄清我的理解,优先级队列将存储最佳路径?所以细胞和累积距离。因为,Dijstra 的算法使用 BFS,在这种情况下会搜索所有邻居以获得最短距离。

最佳答案

将“节点”设置为具有 3 个字段(行、列、距离)并实现 Comparable 的类。然后使用使用PriorityQueue<Node> :

import java.util.PriorityQueue;

class Main {

    public static void main(String[] args) {
        PriorityQueue<Node> pq = new PriorityQueue<>();
        pq.add(new Node(2, 3, 12));
        pq.add(new Node(0, 9, 1));
        pq.add(new Node(4, 0, 8));

        System.out.println(pq.poll().getDistance()); //prints 1
    }
}

class Node  implements Comparable<Node>{

    private final int row, col, distance;

    public Node(int row, int col, int value) {
        this.row = row;
        this.col = col;
        distance = value;
    }

    int getDistance() {
        return distance;
    }

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

或者设置 Comperator到优先级队列所以 Node不必实现Comparable :

import java.util.PriorityQueue;

class Main {

    public static void main(String[] args) {
        PriorityQueue<Node> pq = new PriorityQueue<>(Node::compare);
        pq.add(new Node(2, 3, 12));
        pq.add(new Node(0, 9, 1));
        pq.add(new Node(4, 0, 8));

        System.out.println(pq.poll().getDistance()); //prints 1
    }
}

class Node{

    private final int row, col, distance;

    public Node(int row, int col, int value) {
        this.row = row;
        this.col = col;
        distance = value;
    }

    int getDistance() {
        return distance;
    }

    public static int compare(Node o1, Node o2) {
        return Integer.compare(o1.getDistance(), o2.getDistance());
    }
}

您还可以使用 lambda 表达式来设置比较器:

PriorityQueue<Node> pq = new PriorityQueue<>((o1,o2)->Integer.compare(o1.getDistance(), o2.getDistance()));

所有三个选项均有效。

关于java - 如何将网格中单元格的邻居存储到优先级队列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61536288/

相关文章:

c++ - 尝试实现

java - 当构造函数具有类的类型时,这意味着什么?

java - 为什么它为两个字符串对象生成相同的哈希码?

javascript - 递归函数没有在嵌套循环中被调用

algorithm - 从 9 枚硬币的列表中找出假币

algorithm - "random key dictionary"结构的实际名称是什么?

java - LinkedList 数据结构,为什么我们需要从不同的构造函数调用空的默认构造函数

java - 对哈夫曼树感到困惑

java - hive 服务器未启动

java - AQL-在 Arangodb 中可以实现预期连接以及如何实现?