在二维数组中查找有效邻居

编程入门 行业动态 更新时间:2024-10-10 05:18:03
本文介绍了在二维数组中查找有效邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以,我有一个 4x4 的 2D 数组(它总是这些维度).从数组上的一个位置开始,一些行和列,我想找到它的所有有效邻居.到目前为止,我有一个非常笨拙的实现.

So, I have a 4x4 2D array (it will always be these dimensions). Starting with a location on the array, some row and column, I want to find all of its valid neighbors. So far, I have a really clunky implementation.

//add row if ( !((row + 1) > 3)) { //do stuff } //sub row if ( !((row - 1) < 0)) { //do stuff } //add col if ( !((col + 1) > 3)) { //do stuff } //sub col if ( !((col - 1) < 0)) { //do stuff } ... and so on

这太残忍了.当我开始知道元素的位置时,我觉得我不需要检查每个邻居.有什么想法吗?

This is brutal. I feel like I do not need to check every single neighbor when I start by knowing the location of the element. Any ideas?

推荐答案

对于任何二维数组 cellValues[][] 的 (x,y) 维度下面的代码都可以用于获取任何单元格 (i,j) 的所有 8 个邻居.默认情况下,代码将返回 0.

For any 2D array cellValues[][] of (x,y) dimensions below code can be used for getting all 8 neighbors for any cell (i,j). Code will return 0 by default.

public static ArrayList<Integer> getNeighbors(int i, int j, int x, int y, int[][] cellValues) { ArrayList<Integer> neighbors = new ArrayList<>(); if(isCabin(i, j, x, y)) { if(isCabin(i + 1, j, x, y)) neighbors.add(cellValues[i+1][j]); if(isCabin(i - 1, j, x, y)) neighbors.add(cellValues[i-1][j]); if(isCabin(i, j + 1, x, y)) neighbors.add(cellValues[i][j+1]); if(isCabin(i, j - 1, x, y)) neighbors.add(cellValues[i][j-1]); if(isCabin(i - 1, j + 1, x, y)) neighbors.add(cellValues[i-1][j+1]); if(isCabin(i + 1, j - 1, x, y)) neighbors.add(cellValues[i+1][j-1]); if(isCabin(i + 1, j + 1, x, y)) neighbors.add(cellValues[i+1][j+1]); if(isCabin(i - 1, j - 1, x, y)) neighbors.add(cellValues[i-1][j-1]); } return neighbors; } public static boolean isCabin(int i, int j, int x, int y) { boolean flag = false; if (i >= 0 && i <= x && j >= 0 && j <= y) { flag = true; } return flag; }

更多推荐

在二维数组中查找有效邻居

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

发布评论

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

>www.elefans.com

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