2012-08-06 44 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与一些边界检查。