在二维数组中寻找邻居 [英] Finding neighbours in a two-dimensional array

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

问题描述

有没有一种简单的方法可以在二维数组中找到一个元素的邻居(即一个元素周围的八个元素)?只是在不同的组合中减去和添加索引,就像这样:

Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding to the index in different combinations, like this:

array[i-1][i]
array[i-1][i-1]
array[i][i-1]
array[i+1][i]

...等等.

推荐答案

(伪代码)

row_limit = count(array);
if(row_limit > 0){
  column_limit = count(array[0]);
  for(x = max(0, i-1); x <= min(i+1, row_limit); x++){
    for(y = max(0, j-1); y <= min(j+1, column_limit); y++){
      if(x != i || y != j){
        print array[x][y];
      }
    }
  }
}

当然,这几乎与原始硬编码解决方案一样多,但是有了这个,您可以尽可能多地扩展邻居"(2-3 个或更多单元格)

Of course, that takes almost as many lines as the original hard-coded solution, but with this one you can extend the "neighborhood" as much as you can (2-3 or more cells away)

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

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