Finding valid neighbors in 2D array

前端 未结 7 561
情书的邮戳
情书的邮戳 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条回答
  •  天涯浪人
    2021-01-22 07:31

    public class FindingNeighboursInMatrix {
    
    public static void main(String[] args) {
        int array[][] = { { 1, 2, 3, 4 }, 
                          { 5, 6, 7, 8 }, 
                          { 9, 10, 11, 12 } };
    
        for (int i = 0; i < array.length; i++) {
    
            for (int j = 0; j < array[0].length; j++) {
    
                System.out.println("neightbours of " + array[i][j]);
                int neb[] = findneighbours(i, j, array);
                for (int k = 0; k < neb.length; k++) {
                    if (neb[k] != -1) {
                        System.out.print(" " + neb[k] + ",");
                    }
                }
                System.out.println();
            }
    
        }
    
    }
    
    public static int[] findneighbours(int i, int j, int matrix[][]) {
        int neb[] = new int[8];
        // top row
        neb[0] = getvalue(i - 1, j - 1, matrix);
        neb[1] = getvalue(i - 1, j, matrix);
        neb[2] = getvalue(i - 1, j + 1, matrix);
    
        // left element
    
        neb[3] = getvalue(i, j - 1, matrix);
    
        // right element
    
        neb[4] = getvalue(i, j + 1, matrix);
    
        // bottom row
        neb[5] = getvalue(i + 1, j - 1, matrix);
        neb[6] = getvalue(i + 1, j, matrix);
        neb[7] = getvalue(i + 1, j + 1, matrix);
    
        return neb;
    
    }
    
    public static int getvalue(int i, int j, int matrix[][]) {
        int rowSize = matrix.length;
        int colSize = matrix[0].length;
    
        if (i < 0 || j < 0 || i > rowSize - 1 || j > colSize - 1) {
            return -1;
        }
        return matrix[i][j];
    }}
    

提交回复
热议问题