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

查看:34
本文介绍了在二维数组中查找 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)的二维数组中检查 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-1i+1j-1j+1> 都在你的数组范围内.

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

还应该注意的是,虽然这种方法可以在很少的几行内完成您想要完成的工作,但它的可读性要差得多.因此,这种方法应该伴随着非常描述性的评论.此外,这种方法(或任何其他方法)最好包装在适当命名的函数中(例如 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天全站免登陆