C#C
C#2y 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);
    } 


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.
Was this page helpful?