I'm writing a project that requires me to use a graph traversal algorithm over a grid-like structure made up of Units. I'm creating the grid so that each unit of the grid has references to the each of its neighbors:
class Unit {
boolean type, visited;
Unit up, left, down, right;
Unit(Unit u, Unit l, Unit d, Unit r) {
up = u;
left = l;
down = d;
right = r;
}
}
I create a grid of Units by adding a new Unit object to each position with the neighbors in the form of references to other locations in the grid:
Unit[][] grid = new Unit[height][width];
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
grid[i][j] = new Unit(
i == 0 ? null : grid[i - 1][j],
j == 0 ? null : grid[i][j - 1],
i == height - 1 ? null : grid[i + 1][j],
j == width - 1 ? null : grid[i][j + 1]
);
}
}
Unfortunately, whenever some of the grid Units are created, their neighbors are null so they do not hold the correct reference. To solve this I just run this entire algorithm over again so that it has every grid element filled, but this seems like a very inefficient and ugly solution.
What I would like to do is hold the Unit object as a "dynamic" index of the grid so if a certain position gets updated then the neighbor reference in the appropriate Units would also get updated. This acts as a sort of promise by the grid saying that if a position (i, j) becomes filled then the neighboring Units will have the updated information.
Thank you to anyone who can help me solve this!
P.S. I realize that I can store the indexes to the grid in the Unit class for the neighbors but that would restrict me to the specific grid I have in this example and it would make it necessary to make the call to get the item everytime it is updated. I may not want to store it in a two-dimensional array like I do it here, so I want a generalizable system.