查找数组中元素周围的元素 [英] Find elements surrounding an element in an array

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

问题描述

我有一个多维数组,我想获取该数组中特定元素周围的元素。

I have a multidimensional array, I want to get the elements surrounding a particular element in that array.

例如,如果我有以下内容:

For example if I have the following:

[[1,2,3,4,5,6]
 [8,9,7,5,2,6]
 [1,6,8,7,5,8]
 [2,7,9,5,4,3]
 [9,6,7,5,2,1]
 [4,7,5,2,1,3]]

如何查找上述任何元素周围的所有8个元素?我如何处理边缘的元素?

How do I find all the 8 elements around any of the above elements? And how do I take care of elements at the edges?

我想到的一种方法是,为此写一个9行代码,这很明显,但是有更好的解决方案吗?

One way I figured out is, to write a 9 line code for this , which is obvious, but is there a better solution?

推荐答案

for (i = 0; i < array.length; i++) {
            for (j = 0; j < array[i].length; j++) {
                for (x = Math.max(0, i - 1); x <= Math.min(i + 1, array.length); x++) {
                    for (y = Math.max(0, j - 1); y <= Math.min(j + 1,
                            array[i].length); y++) {
                        if (x >= 0 && y >= 0 && x < array.length
                                && y < array[i].length) {
                            if(x!=i || y!=j){
                            System.out.print(array[x][y] + " ");
                            }
                        }
                    }
                }
                System.out.println("\n");
            }
        }

感谢所有回复的人,但我在我刚刚发现的这篇文章的帮助下想出来,以上是解决方案。再次感谢:)

Thanks to all the people who have answered, but i figured it out with the help of this post which i found just now, and above is the solution. thanks again :)

这篇关于查找数组中元素周围的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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