对于任何二维数组cellValues[][]
,(x,y)
以下代码可用于获取任何单元格的所有 8 个邻居(i,j)
。默认情况下将返回代码0
。
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;
}