Finding valid neighbors in 2D array

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

    This is my solution:

    public int[4][4] array2d;
    //don't forget to fill it!
    
    private void adjustNeighbors(int xCoord, int yCoord) {
    
        for (int yi = y-1; yi <= yCoord+1; yi++) {         //loop through the neighbors
    
            for (int xi = x-1; xi <= xCoord+1; xi++) {
    
                try {
    
                    if (!(xCoord != xi && yCoord != yi)) {
                        array2d[y][x]++;  //do whatever you want to all the neighbors!
                    } 
    
                } catch (Exception e) {
                    // something is out of bounds
                }
    
            }
    
        }
    
    }
    

提交回复
热议问题