Finding valid neighbors in 2D array

前端 未结 7 566
情书的邮戳
情书的邮戳 2021-01-22 07:13

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

7条回答
  •  猫巷女王i
    2021-01-22 07:50

    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 getNeighbors(int i, int j, int x, int y, int[][] cellValues) {
        ArrayList 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; 
    }
    

提交回复
热议问题