java - 搜索网格中每个图 block 的相邻图 block 的有效方法?

标签 java

我有这个 A* 搜索算法,生成一个图 block 到另一个图 block 的路径。该算法要求每个图 block 都有一个其邻居的列表,目前我用于搜索每个图 block 的所有相邻图 block 的代码如下所示:

/* PathTile is simply a class that holds an x,y coordinate, an unique ID and 
   an arraylist of neighbouring tiles. A method called intersect() allows me 
   to check if the tile's edge is touching other tiles. */

private void generatePathTileNeighbors()
{
    for(int i = 0; i < pathTiles.size(); i++)
    {
        PathTile thisTile = pathTiles.get(i);

        for(int j = 0; j < pathTiles.size(); j++)
        {
            PathTile otherTile = pathTiles.get(j);
            if(!thisTile.uniqueID.equals(otherTile.uniqueID)){
                if(thisTile.intersect(otherTile)){
                    thisTile.addNeighbor(otherTile);
                    System.out.println(thisTile.uniqueID);
                }
            }
        }
    }
}

我很确定这绝对是最糟糕的方法。对于包含数千个图 block 的网格,加载每个图 block 的所有相邻图 block 需要几分钟的时间。什么是更有效的方法来做到这一点?谢谢!

Text](https://imgur.com/a/huhNBaW.jpg[![enter image description here ] 1 ) - 我的网格是什么样的

最佳答案

为什么不只使用二维数组和索引作为查找邻居的点。 例如,tiles[0][0] 将有邻居tiles[1][0]、tiles[0][1],甚至如果您愿意的话,tiles[1][1]。

此外,最好在图 block 初始化期间添加neighbour。因此你会得到这样的东西

Tile tiles = new Tile[n][m];
for(int i=0; i<n; i++){
   for(int j=0; j<m ; j++){
     Tile tile  = new Tile();
     if(i-1 >= 0)
       tile.addNeighbour(tiles[i-1][j]);
     if(i+1 < n)
       tile.addNeighbour(tiles[i+1][j]);
     if(j-1 >= 0)
       tile.addNeighbour(tiles[i][j-1]);
     if(j+1 < m)
       tile.addNeighbour(tiles[i][j+1]);
     tiles[i][j] = tile;
   }
}

关于java - 搜索网格中每个图 block 的相邻图 block 的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61504357/

相关文章:

java.sql.SQLException : Access denied for user 'root' @'192.168.3.33' (using password: YES) on jelastic

java - 如何在 Java Selenium 中禁用 Chrome 实验选项 Same-site-by-default-cookies?

java - 服务器接受套接字,但之后套接字无法接收任何内容

java - 从 C 创建 JVM

java - 使用 JFrame 登录 JDialog

java - 如何在 DBCP 中使用(useUnicode=yes characterEncoding=UTF-8)

java - AsyncTask 不会在第一次尝试时调用 OnCancel()

java - Spring选择了存储库实现,它甚至没有实现存储库接口(interface)

java - rxJava 和 promises 的关系

java - 如何在 bukkit 中存储变量的变量?