C
C#11mo ago
Tsjech

Recursive method and memory problems

I am implementing the DFS algorithm and I am keeping track of what routes have been passed and their value, the core of the algorithm looks like this:
private void DFSVisitting(Planet current, Planet old, bool[] visited, int len)
{
int length;
length = len;
visited[current.id] = true;
if (!(current == old)) {
foreach (Route route in gameScreen.board.routes) {
if (!(route.color == color && route.built)) continue;
if ((route.planet1 == current && route.planet2 == old) || (route.planet2 == current && route.planet1 == old)) length += route.costs;
}
}

List<Planet> neighbours = adjacent[current.id];
foreach (Planet p in neighbours) {
if (!visited[p.id]) {
DFSVisitting(p, current, visited, length);
// returns here
lengths.Add(length);
length = 0;
}
}
lengths.Add(length);
}
private void DFSVisitting(Planet current, Planet old, bool[] visited, int len)
{
int length;
length = len;
visited[current.id] = true;
if (!(current == old)) {
foreach (Route route in gameScreen.board.routes) {
if (!(route.color == color && route.built)) continue;
if ((route.planet1 == current && route.planet2 == old) || (route.planet2 == current && route.planet1 == old)) length += route.costs;
}
}

List<Planet> neighbours = adjacent[current.id];
foreach (Planet p in neighbours) {
if (!visited[p.id]) {
DFSVisitting(p, current, visited, length);
// returns here
lengths.Add(length);
length = 0;
}
}
lengths.Add(length);
}
the problem is, if the network is searching down a path and ends in a dead at the function returns at the place of my comment, but the length variable has been forgotten by the program (atleast what i think) because this method has been called multiple times already and is now returning to an older instance of itself. So is there any way to surpass this issue? Nodes are planets and Edges are Routes.
5 Replies
Tsjech
TsjechOP11mo ago
@TeBeCo
Unknown User
Unknown User11mo ago
Message Not Public
Sign In & Join Server To View
Tsjech
TsjechOP11mo ago
hmm returning a value wouldnt be handy, because it generally needs to forget the when it finds a dead end and grab the one it was working on before that branch. but thank you
Unknown User
Unknown User11mo ago
Message Not Public
Sign In & Join Server To View
Tsjech
TsjechOP11mo ago
I just fed the nodes ive been at to the method itself using its params, so i didnt have to return anything but it did keep track of old data when it popped
Want results from more Discord servers?
Add your server