Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
879 views
in Technique[技术] by (71.8m points)

java - Finding valid neighbors in 2D array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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; 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...