Finding valid neighbors in 2D array

前端 未结 7 555
情书的邮戳
情书的邮戳 2021-01-22 07:13

So, I have a 4x4 2D array (it will always be these dimensions). Starting with a location on the array, some row and column, I want to find all of its valid neighbors. So far, I

7条回答
  •  时光说笑
    2021-01-22 07:31

    Here's how I'd do it: a method that gets a list of x,y pairs for valid neighbors, given an arbitrary [x,y] point and generalized to any array size:

    public List getNeighbors(x, y, maxX, maxY) {
        neighbors = new ArrayList;
        if x > 0:
            neighbors.add({x-1, y});
        if y > 0:
            neighbors.add({x, y-1});
        if x < maxX:
            neighbors.add({x+1, y});
        if x < maxY:
            neighbors.add({x, y+1});
        return neighbors;
    }
    
    [...]
    
    for (int[] coords : getNeighbors(x, y, 4, 4)) {
        // do stuff
    }
    

提交回复
热议问题