在二维数组中查找8个邻居

编程入门 行业动态 更新时间:2024-10-10 15:24:45
本文介绍了在二维数组中查找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个邻居

本文发布于:2023-11-30 15:50:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   邻居

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!