I've been doing this code to make a maze and solve it. The first creates a vector of panels and labels, the panels are the squares of the board, and the text of the labels says if it is a wall (#), free path (+), path already crossed (-), the beginning (/ ), or the end or the exit (*).
void generaTableroLaberinto()
{
/*Genera la cuadricula completa del laberinto, con un label con un # lo que significa que ese panel es un muro*/
tablero = new Panel[tamañoLaberinto * tamañoLaberinto];
indice = new Label[tamañoLaberinto * tamañoLaberinto];
int a;
for (int i = 0; i < tamañoLaberinto*tamañoLaberinto; i++)
{
a = azar.Next(1, 5);
tablero[i] = new Panel();
tablero[i].BackColor = Color.Beige;
tablero[i].Width = 40;
tablero[i].Height = 40;
tablero[i].BorderStyle = BorderStyle.FixedSingle;
//----------------------------------------------------
indice[i] = new Label();
/*Le da valores de # y + al laberinto al azar*/
if (a == 1)
{
indice[i].Text = "#";
}
else
{
indice[i].Text = "+";
}
// indice[i].Text = (i).ToString();
indice[i].Visible = true;
indice[i].AutoSize = true;
//----------------------------------------------------
indice[i].Show();
tablero[i].Show();
tablero[i].Controls.Add(indice[i]);
//Muestra el vector en forma de tablero----------------------------------------------------
if (i == 0)
{
tablero[i].Location = new Point(20, 20);
tablero[i].BackColor = Color.Orange;
indice[i].Text = "/";
}
else
{
if(i % tamañoLaberinto == 0)
{
tablero[i].Location = new Point(tablero[i-tamañoLaberinto].Location.X, tablero[i-tamañoLaberinto].Location.Y + 40);
}
else
{
tablero[i].Location = new Point(tablero[i-1].Location.X + 40, tablero[i-1].Location.Y);
}
}
if(i == (tamañoLaberinto*tamañoLaberinto) - 1)
{
tablero[i].BackColor = Color.Green;
indice[i].Text = "*";
}
panel1.Controls.Add(tablero[i]);
}
}
And it goes through it until the end, the panels are red, but when executing this part the error "System.StackOverflowException" appears in the first if, and I do not know why
void solucionLaberinto(int x1)
{ Boolean termina = false;
int x2, k;
k = 0;
int[] mov = new int[5];
mov[1] = 1;
mov[2] = -1;
mov[3] = tamañoLaberinto;
mov[4] = -tamañoLaberinto;
//-------------------------
do
{
k = k + 1;
x2 = x1 + mov[k];
if (indice[x2].Text.Equals("+"))
{
//tablero[x2][y2] = s;
tablero[x2].BackColor = Color.Red;
if (indice[x2].Text != "*")
{
solucionLaberinto(x2);
if (!termina)
{
indice[x2].Text = "-";
}
}
else
{
termina = true;
}
}
} while (k < 4 && !termina);
}