将地图图像转换为二维数组。算法dfs,bfs,astar

时间:2015-11-20 16:21:49

标签: java image algorithm breadth-first-search

我有问题如何从这个程序开始。 我想获得2d像素本地化阵列。 然后使用bfs,dfs处理此数组,以获取从橙色点到绿色点的路径。 如果访问则绘制灰色像素。 绘制路径并将其保存到其他图像。

当我处理这个时,我想改变每个像素的成本(通过绘制类似于墙壁的油漆,但它可以通过它们以更高的成本来完成)

    public int [][] gRGB(BufferedImage image)
{
    int width = image.getWidth();
      int height = image.getHeight();
      int[][] result = new int[width][height];

      for (int row = 0; row < width; row++) {
         for (int col = 0; col < height; col++) {

            result[row][col] = image.getRGB(row, col);
         }
      }

      return result;
}
}

从这段代码中我得到2d-array满-1的值。是否有选项可以将颜色信息作为值(不是rgb我希望将其作为一个数字而不是4)

编辑:

protected static int [][] convert(BufferedImage image)
{
    int width = image.getWidth();
    int height = image.getHeight();

    int[][] result =  new int [width][height];

    for(int row = 0; row < height; row++)
        for(int col = 0; col < width; col++)
        {
            Color c = new Color(image.getRGB(col, row));
            String h = String.format("%02x%02x%02x", c.getRed(),c.getGreen(),c.getBlue());

            if(h.equals("000000"))     // black
            {
                result[col][row] = 0;
            }
            else if(h.equals("fe0000")) // red
            {
                result[col][row] = 5; 
            }
            else if(h.equals("ffffff")) // white
            {
                result[col][row] = 1;
            }
            else if(h.equals("ff7d41")) // orange - start
            {
                result[col][row] = 10;
            }
            else if (h.equals("ff0078")) // pink - end
            {
                result[col][row] = 9;
            }
            else
            {
                result[col][row] = 3;
            }

        }

    for(int row = 0; row < height; row++)
    {
        System.out.println();
        for(int col = 0; col < width; col++)
            System.out.print("\t" + result[col][row]);
    }

    return result;      
}

所以我现在有了像素值数组。谁能解释一下如何编写DFS或BFS算法?成本是像素的值?

Black - walls, Orange dot - start, Green dot - end

1 个答案:

答案 0 :(得分:0)

为了以最低成本找到路径,最好使用诸如UCS,A *或IDA *之类的算法(使用BFS或DFS在加权图上找到最短路径是非常低效的)。我的建议是首先实现UCS,然后使用简单的启发式(例如曼哈顿到A *的距离)来改进它。有关UCS和A *的完整说明,请参阅以下链接:

Wikipedia A*
Wikipedia UCS

至于在2D阵列上使用这些算法,您应该将每个点都视为一个节点,并将该节点连接到每个邻居节点。所以每个节点都连接到它的4个非墙邻居(如果你可以对角移动,则连接8个非墙邻居)。