M
M
Maria2018-04-06 17:47:05
recursion
Maria, 2018-04-06 17:47:05

Why is the recursion not interrupted after the stop condition is met?

When I go through the code in VS step by step, I see the following picture ... which is not clear to me at all: why, after the recursion stop condition is met, the program jumps first to the end of the function, and then goes clearly to recursion, bypassing even the for loop in which it nested More details: I'm trying to recursively go through the graph's adjacency matrix and find paths of length 2 (ie paths that go through 3 points). In this example, I am looking for paths that start from the top of the graph numbered 3 (3rd row of the matrix).if (path.Count == pathLength+1)
5ac7884f8ea36667004195.jpeg
I believe that the function I wrote should give me the path 3-1-5, since I did not write any check for the remaining units in the row. But instead, the function, after finding this path, goes back to recursion .. I can not understand why this happens. Tell me, please, why?
The code:

namespace Lab4{

    class Program
    {
        public static int v = 8;
        public static int pathLength = 2;
        public static List<int> path = new List<int>();

        public static int[,] matrix = {
                { 0, 0, 0, 0, 1, 0, 0, 0 },
                { 1, 0, 0, 0, 0, 0, 0, 0 },
                { 1, 1, 0, 0, 0, 1, 0, 0 },
                { 0, 0, 0, 0, 0, 0, 1, 0 },
                { 0, 0, 0, 1, 0, 0, 0, 0 },
                { 0, 0, 0, 0, 1, 0, 0, 0 },
                { 0, 0, 0, 0, 0, 1, 0, 0 },
                { 0, 0, 0, 0, 0, 0, 1, 0 }
            };
        
        public static void recursion(int row)
        {
            if (path.Count == pathLength+1)
            {
                for (int k = 0; k < path.Count; k++)
                {
                    Console.Write(path[k] + " ");
                }
                Console.ReadKey();
            }
            else
            {
                for (int j = 0; j < v; j++)
                {
                   if (matrix[row,j] == 1)
                   {
                        path.Add(row+1);
                        recursion(j);
                   }  
                }
            }
        }
        static void Main(string[] args) {
            recursion(2);
            Console.ReadLine();          
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cicatrix, 2018-04-06
@cicatrix

Hint: look at the call stack. You exit the function and "go up" one level up.
That is, earlier you recursively entered the recursion function, then it worked and went to the frame above.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question