发现在二维数组有效邻 [英] Finding valid neighbors in 2D array

查看:109
本文介绍了发现在二维数组有效邻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个4×4的二维数组(它将永远是这些尺寸)。与阵列上的位置,一些行和列的开始,我想找到它的所有有效的邻居。到目前为止,我有一个很笨重的实现。

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 have a really clunky implementation.

//add row
    if ( !((row + 1) > 3)) {
        //do stuff
    }
    //sub row
    if ( !((row - 1) < 0)) {
        //do stuff
    }
    //add col
    if ( !((col + 1) > 3)) {
        //do stuff
    }
    //sub col
    if ( !((col - 1) < 0)) {
        //do stuff
    }
... and so on

这是残酷的。我觉得我并不需要检查每一个邻居,当我开始通过了解元素的位置。任何想法?

This is brutal. I feel like I do not need to check every single neighbor when I start by knowing the location of the element. Any ideas?

推荐答案

下面是我会怎么做:那得到的x,y对的有效邻居列表的方法,给出一个任意 [ X,Y] 点与广义任何数组大小为:

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<int[]> getNeighbors(x, y, maxX, maxY) {
    neighbors = new ArrayList<int[]>;
    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
}

这篇关于发现在二维数组有效邻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆