在二维数组中查找8个邻居 [英] Finding 8 neighbours in 2d Array

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

问题描述

我到处都在寻找这个问题,有一些关于这个问题的答案,但是没有一个我真正理解/不适合我的。

I have looked around for this question, there are some answers about the question, but none that i really understand/or is not suitable for me.

所以我的问题是在包含*或O的2d数组中检查8个邻居。

So my problem is to check for 8 neighbors in an 2d array containing chars, either * or O.

代码:

aliveCheck = isAlive(g,row,column-1);
if(aliveCheck){
    aliveCounter++;
}

aliveCheck = isAlive(g,row,column+1);
if(aliveCheck == 1){
    aliveCounter++;
}

aliveCheck = isAlive(g,row+1,column);
if(aliveCheck == 1){
    aliveCounter++;
}

对所有8个邻居来说,这都是可行的,但是我不高兴

Etc for all the 8 neighbours, this works, but I'm not happy with the solution.

isAlive()是一个简单的函数,用于确定坐标是*还是O。

isAlive() is a simple function to findout if a coordinate is * or O.

有人对此问题有更好的解决方案,或者有任何改进建议吗?

Anyone got a better solution to this problem or got any tips on how to improve it?

谢谢

推荐答案

for(int i=-1, i<=1; ++i) {
    for(int j=-1; j<=1; ++j {
        if((i || j) && isAlive(g,row+i,column+j)) {
            aliveCounter++; } } }

此方法假定 i-1 i + 1 j-1 j + 1 都是在数组的边界之内。

This method assumes that i-1, i+1, j-1, and j+1 are all within the bounds of your array.

还应该注意的是,尽管这种方法可以在很少的几行中完成您要完成的工作,但要少得多因此,此方法应带有描述性很强的注释。最好将ach(或任何其他方法)包装在适当命名的函数中(例如 checkNeighbors )。

It should also be noted that while this approach accomplishes what you're trying to accomplish in a very few number of lines, it's far less readable. As such, this approach should be accompanied with very descriptive comments. Moreover, this approach (or any other method) would be best wrapped in an appropriately named function (such as checkNeighbors).

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

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