在二维数组中查找邻居

时间:2017-01-09 20:40:36

标签: java multidimensional-array

我正在创建一个深度优先搜索程序,它搜索2d数组以找到数字1并始终从0开始。我在查找数组中每个元素的邻居时遇到一些麻烦,我有一个方法(基于这里找到的伪代码Finding neighbours in a two-dimensional array):

private static void findNeighbour(Integer[][] maze) {

    int row = 0;
    int col = 0;

    int row_limit = maze.length;
    if(row_limit > 0){
     int column_limit = maze[0].length;
     for(int y = Math.max(0, col-1); y <= Math.min(col+1, column_limit); y++){
      for(int x = Math.max(0, row-1); x <= Math.min(row+1, row_limit); x++){
          if(x != row || y != col){
           // printArray(maze);
            neighbours.push(x);
            neighbours.push(y);
          }
        }
      }
    }    


}

基本上我试图通过2d数组,找到每个邻居然后将邻居放入堆栈中,这样我就可以将它们从dfs中的堆栈中弹出。我把我正在使用的迷宫和我目前得到的输出放在一起。如果有人能指出我正确的方向/指出任何似乎导致它不能找到邻居的事情,我将不胜感激。

迷宫:

static Integer[][] maze = { { 11, 3 }, { 2, 3 }, { 0, 3 }, { 1, 4 }, { 5, 4 }, { 5, 7 }, { 6, 7 }, { 7, 8 }, { 8, 9 },
        { 9, 10 }, { 0, 5 } };

输出:

[1, 0, 0, 1, 1, 1]

1 个答案:

答案 0 :(得分:2)

逻辑很好。您可以使用int代替Integer对象包装器。 使用一些数据结构也会更好。行/ y通常是垂直maze[y],列是水平maze[y][x],因此maze[y]是水平线。

private static List<Point> findNeighbours(int[][] maze, Point pt) {
    List<Point> neighbours = new ArrayList<>(8); // Reserve only 8 points
    int height = maze.length;
    if (height > 0) {
        int width = maze[0].length;
        for (int y = Math.max(pt.y - 1, 0); y <= Math.min(pt.y + 1, height); ++y) {
           for (int x = Math.max(pt.x - 1, 0); x <= Math.min(pt.x + 1, width); ++x) {
               if (!(y == pt.y && x == pt.x)) {
                   neighbours.add(new Point(x, y));
               }
           }
        }
    }
    return neighbours;
}

存在的技术是:

  • 在迷宫周围使用墙壁,以便考虑点从(1,1)开始,不需要边界检查。
  • 使用8个增量的数组:`{(-1,-1),...,(1,1)}。
相关问题