Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Efficient algorithm for getting grid neighbors?

843785Mar 9 2009 — edited Mar 10 2009
Hi all,

I have a program in which I have a grid. I need a simple way to get the neighbors of any square. (Diagonal neighbors are included, so a square in the middle would have eight neighbors). I wrote one, below, when I originally intended the grid to wrap. However, I've now decided that wrapping, north-south and east-west, is optional, so I have to account for cases where it might not wrap.

Now, I could easily add an if..then to every line that I'm adding the neighbors (shown commented out), but this looks really, really ugly. Can any of the wizards here work out an efficient, clean way to do this?

Thanks!
	public Vector getNeighbors(EnvironmentUnit environmentUnit)
    {
	    int x = environmentUnit.getXLoc();
	    int y = environmentUnit.getYLoc();
	    
	    int left = (x == 0) ? columns - 1 : x - 1;
	    int right = (x == columns - 1) ? 0 : x + 1;
	    int top = (y == 0) ? rows - 1 : y - 1;
	    int bottom = (y == rows - 1) ? 0 : y + 1;
	    
	    Vector neighbors = new Vector();
	    
	    // Not accounting for wrapping:
	    
	    neighbors.add(envUnits[left][top]);
	    neighbors.add(envUnits[x][top]);
	    neighbors.add(envUnits[right][top]);
	    neighbors.add(envUnits[left][y]);
	    neighbors.add(envUnits[right][y]);
	    neighbors.add(envUnits[left][bottom]);
	    neighbors.add(envUnits[x][bottom]);
	    neighbors.add(envUnits[right][bottom]);
	    
	    // Ugly way to do the above accounting for wrapping:
	    
	    if ((wrapEastWest && wrapNorthSouth) || (x != 0 && y != 0)){
	    	neighbors.add(envUnits[left][top]);
	    }
	    if (wrapNorthSouth || y != 0){
	    	neighbors.add(envUnits[x][top]);
	    }
	    // etc. etc.
	    
	    return neighbors;
    }
Edited by: TimQuinn on Mar 9, 2009 7:56 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 7 2009
Added on Mar 9 2009
8 comments
3,995 views