Answer the question
In order to leave comments, you need to log in
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)
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question