Finding valid neighbors in 2D array

前端 未结 7 559
情书的邮戳
情书的邮戳 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:54

    What constitutes a valid neighbor?

    If all you want is to retrieve all the neighbors of a cell within the bounds of the array (including diagonals), this will suffice.

    public List<Element> getNeighbors( int x, int y ) {
        List<Element> neighbors = new ArrayList<>();
    
        for( int i = -1; i <= 1; ++i ) {
            for( int j = -1; j <= 1; ++j ) {
                if( i == 0 && j == 0 ) {
                    continue;
                }
                if( i + x >= 0 && i + x < array.length &&
                    j + y >= 0 && j + y < array[0].length ) {
                        // we found a valid neighbor!
                        neighbors.add( array[i][j] );
                }
            }
        }
    
        return neighbors;
    }
    
    0 讨论(0)
提交回复
热议问题