【问题标题】:How can I determine the shortest distance from a certain type of vertex for all vertices?如何确定所有顶点与某种类型顶点的最短距离?
【发布时间】:2021-08-08 12:54:43
【问题描述】:

我有一个表示地图的网格。我有海洋节点,我有陆地节点。我想使用递归函数为每个人分配一个距离。 (所以我猜是一个函数调用/孤岛)。

我目前有一个代码,是这样的:

    public int searchOcean(int x, int y, boolean[] visited) {

        if (x < 0 || x >= width || y < 0 || y >= height) {
            return 1000;
        }

        Node current = this.get(x, y);

        int index = current.getIndex(this);

        if (visited[index]) {
            return current.oceanDist;
        }

        visited[index] = true;

        if (current.ocean) {
            current.oceanDist=0;
            return 0;
        }

        int r1 = searchOcean(x + 1, y, visited);
        int r2 = searchOcean(x - 1, y, visited);
        int r3 = searchOcean(x, y + 1, visited);
        int r4 = searchOcean(x, y - 1, visited);

        int min = Math.min(Math.min(r1, r2), Math.min(r3 , r4))+1;

        current.oceanDist = min;

        return min;
    }

问题是,它并没有真正起作用,我想主要是因为我不知道如何处理已经访问过的节点。

【问题讨论】:

    标签: java recursion distance graph-theory flood-fill


    【解决方案1】:

    你想要 Dijkstra 算法https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

    Loop A over nodes that are land
        Apply Dijkstra
        Loop B over nodes that are land
            add distance ( given by Dijkstra ) from A to B to results.
    

    或更好(删除不需要的 Dijkstra 调用)

    construct empty D to store distances between every pair of land nodes
    loop A over every land node
         loop B over every land node
              if A-B NOT saved into D
                   apply Dijkstra with source A
                   loop C over land nodes
                        save distance A-C into D
                        break out of loop B
    

    D 是由有序节点对 A,B 键入的距离映射。即 A->B 和 B->A 给出相同的距离。

    【讨论】:

    • 天哪,我太笨了。我们上学期刚学过,但我非常专注于洪水填充算法。非常感谢。
    • 执行此操作的速度有多快?我有一个运行速度非常慢的算法,因为它遍历每个陆地节点,然后是每个邻居。它基本上是一个 BFS,我知道 Dijkstra 与它非常相似。
    • 速度?您必须为每个陆地节点调用一次 Dijkstra。在线资源会告诉你 Dijkstra 的速度。
    • 哦,我认为存储部分结果是可能的。
    • 你是对的,因为距离 A->B 将与 B->A 相同,因此无需为每个节点对调用 Dijsktra
    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    相关资源
    最近更新 更多