I have a bunch of integers in a 2D array (int[,]), all set with multiple different values. I want a list of them in order from one point back around to itself.

So imagine a grid that’s red. then there’s a “cube” of green points on that grid. I want to pick one green point on that grid, and then that point checks for another green point above it, to the top right, the right, ect. Then, at the first point it finds, I want to do the same thing, again and again, unit it reaches either the point that it started with or comes back with no point. Each of these points needs to be added to a list, in the order they are found.

I usually would use for loops for this, which is how I set each point, but the problem is that it doesn’t correctly order them. I need to set, up, as the title says, a “chain” system to go from one to the next point.

I’ve been trying to redo Dijkstra’s Algorithm to work with this, but I can’t manage to find a way to.

Any help would be greatly appreciated, thanks in advance. -Rio

The family of search algorithms are mostly all related, but a basic recursive depth-first search may be simpler to implement for your needs. The pseudocode on Wikipedia is nice and short:

procedure DFS(G,v):
label v as discovered
for all edges from v to w in G.adjacentEdges(v) do
if vertex w is not labeled as discovered then
recursively call DFS(G,w)

You could implement this any number of ways. Here are some suggestions for a simple implementation.

Set up another 2D array of bools (bool[,]) named discovered. You’ll use this to remember which nodes you’ve already visited. Initialize it all to false before you start the search. As you visit each node, set the corresponding bool to true.

When you start, in the first level of recursion (that is, the nodes next to the starting point), don’t follow the edge back to the starting point. You want it to go out first before looping back.

When you reach the starting point again, stop. As you unwrap the recursion, you’ll get the path in reverse order.

Set up a simple test scene with a small 2x2 grid. Add a Debug.Log line to DFS() that reports which node it’s checking. When you run the scene, the Console will give you a trace of which nodes it followed.