2012-08-06 110 views
-2

我有一個數組,存儲在4X4網格,0,1,2,3等單元格的索引。我知道,直接在項目0旁邊是項目1(右)和項目4(下面)。我將如何編寫一個函數,返回直接在傳入的索引旁邊的單元格的索引?4X4網格中的哪些單元格彼此相鄰?

function getCellsAround(0) 
{ 
    should return 1 and 4 
} 
+0

這是功課嗎? – 2012-08-06 21:36:15

+0

你剛剛用英語向我們描述了它。您需要概括並將其轉換爲代碼。你在某個特定點上掙扎嗎? – jeff 2012-08-06 21:36:56

+0

看起來你想在x和y座標中使用'+ 1'和' - 1%4'嗎?你還需要函數 – Carl 2012-08-06 21:37:21

回答

2
public static ArrayList<Point> getPointsAround(Point p, Rectangle r) { 
    ArrayList<Point> points = new ArrayList<Point>(); 
    for(int dx = -1; dx <= 1; dx++) { 
     for(int dy=-1; dy <= 1; dy++) { 
      if(dx!=0 || dy !=0) { 
       Point point = new Point(p.x+dx, p.y+dy); 
       if(r.contains(point)) { 
        points.add(point); 
       } 
      } 
     } 
    } 
    return points; 
} 

類似的東西?使用X,Y座標(Point類),而不是隻:

(1,2,3

4,5,6)

1

這聽起來像功課給我,所以這裏有一個總體思路。

爲每種類型的鄰居製作一個函數。既然你寫了這麼多種語言,不知道你實際使用的是什麼。這裏的java

private Integer getTopNeighbor(int ind) // .... 
private Integer getBottomNeighbor(int ind) // .... 
private Integer getLeftNeighbor(int ind) // .... 
private Integer getRightNeighbor(int ind) // .... 

public Integer[] getAllNeighbors(int ind) // use the four above to determine 

然後其中一些可能會爲空(如第一個索引0不會有左邊或頂部的鄰居)。所以檢查所有這些並返回非空的。

爲了讓你開始,getRightNeighbor將ind + 1與一些邊界檢查。