© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
23 replies
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
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.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Memory Referrence Issue In Recursive Algorithm
C#CC# / help
3y ago
❔ Help with C# TSP recursive method
C#CC# / help
3y ago
❔ Recursive Multiplier
C#CC# / help
3y ago
✅ Recursive type definition
C#CC# / help
3y ago