-2

我有一个数组,将单元格的索引存储在 4X4 网格中,0、1、2、3 等。我知道紧挨着项目 0 的是项目 1(右侧)和项目 4(下)。我将如何编写一个函数来返回与传入的索引直接相邻的单元格索引?

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

2 回答 2

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)

于 2012-08-06T21:38:16.307 回答
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 并进行一些边界检查。

于 2012-08-06T21:42:04.230 回答