I’m doing my first algorithm (A* Pathfinding) and part of it involves checking all nodes adjacent to a different node. Is there a quick and easy way to do this or must it be done manually for each node?
Edit:
By adjacent I mean this:
Each X is adjacent to the parent node, O
XXX
XOX
XXX
There’s a nice double-for-loop you can use:
This can also be generalized to only consider points adjacent by cardinal directions (i.e. directly up/down/left/right). To do that, you use a modification of the above for loop where you visit all eight neighbors, but then skip points that either
i == xandj == y), ori != xandj != y)Interestingly, the above two tests can be rolled into one line:
((i == x) == (j == y)). This tests whether both values are the same (you’re at the same place you started) or both values are different (you’re on a diagonal):Of course, in both cases you should ensure that you’re within the bounds of the world, but since I don’t know how those are specified I’ll leave it as an exercise to the reader. 🙂
Hope this helps!