2017-01-09 47 views
0

我創建了一個深度優先搜索程序,該程序通過搜索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); 
      } 
     } 
     } 
    }  


} 

從本質上講,我試圖去通過二維數組,找到每個鄰居然後將鄰居到堆棧,所以我可以彈出他們在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] 
+0

它看起來很適合我。 (0,0)的鄰居是(1,0),(0,1)和(1,1),這就是'neighbors'中的內容。你期望它包含什麼? (順便說一句,你的循環應該有'Math.min(col + 1,column_limit-1)'和'Math.min(row + 1,row_limit-1)',因爲數組的長度是非法索引數組,或者將'row_limit'設置爲'maze.length-1',對於'column_limit'也是如此。) –

+0

@TedHopp啊,這是有道理的,我認爲它顯示了數組中的實際元素(我真正想要的)作爲與座標相反。 –

+0

這不是實現它的真正方法...爲什麼不嘗試使用遞歸函數來實現它?害怕遞歸堆棧的stackoverflow? –

回答

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)}。
+0

謝謝你解釋得這麼好,真的有幫助,我唯一的問題是關於點。有沒有辦法將它推入堆棧而不是將其添加到數組列表中?我只問,因爲數據將如何使用。 –

+1

如果你使用一堆點,比如'Deque stack = new ArrayDeque <>();'('Deque'是比舊的'Stack'更現代的版本)。如[Stack本身]的javadoc所述(https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html) –