Question by
TheUberMedic · Mar 09, 2018 at 11:54 AM ·
recursionstackoverflow
Stack Overflow error in recursive method
I'm trying to use a recursive algorithm to solve a maze. How I'm trying to get it to work is to create a list of stacks of vectors. The algorithm will check the latest stack and peek the top which then creates another stack containing that vectors neighboughing cells that can be visited. Once the player's vector location is found, the program stops and gets the top of all the stacks in the list as the path to follow. The problem is that it creates a stack overflow error and crashes Unity once alert is set to true. I know that the program works if I make it iterative but that won't always find the player's location if they're too far away.
public class EnemyMovement : MonoBehaviour {
public bool Alert;
public GameObject player;
private Vector2 PLoci;
private bool[,,] grid;
private bool[,] VisitedCells;
private static void PathFinder(List<Stack<Vector2>> movement, bool[,,] grid, Vector2 PLoci, bool[,] VisitedCells)
{
if (movement[movement.Count - 1].Peek() != PLoci)
{
var temp = movement[movement.Count - 1].Peek();
int x = (int)temp.x;
int z = (int)temp.y;
VisitedCells[x, z] = true;
movement.Add(new Stack<Vector2>());
if (grid[x, z, 0] == false)
{
if(z + 1 < Maindata.Size)
{
if (!VisitedCells[x, z + 1])
{
movement[movement.Count - 1].Push(new Vector2(temp.x, temp.y + 1));
}
}
}
if (grid[x, z, 1] == false)
{
if (x + 1 < Maindata.Size)
{
if (!VisitedCells[x + 1, z])
{
movement[movement.Count - 1].Push(new Vector2(temp.x + 1, temp.y));
}
}
}
if (grid[x, z, 2] == false)
{
if (z - 1 > 0)
{
if (!VisitedCells[x, z - 1])
{
movement[movement.Count - 1].Push(new Vector2(temp.x, temp.y - 1));
}
}
}
if (grid[x, z, 3] == false)
{
if (x - 1 > 0)
{
if (!VisitedCells[x - 1, z])
{
movement[movement.Count - 1].Push(new Vector2 (temp.x - 1, temp.y));
}
}
}
if (movement[movement.Count - 1].Count == 0 & movement.Count != 1)
{
movement.Remove(movement[movement.Count - 1]);
}
PathFinder(movement, grid, PLoci, VisitedCells);
}
}
private void Update()
{
if (Alert == true)
{
grid = Maindata.Grid;
//Get cell location of player
PLoci = new Vector2(((int)(player.transform.position.x) - ((int)player.transform.position.x % 5)) / 10, ((int)(player.transform.position.z) - ((int)player.transform.position.z % 5)) / 10);
VisitedCells = new bool[Maindata.Size, Maindata.Size];
for (int x = 0; x < Maindata.Size; x += 1)
{
for (int z = 0; z < Maindata.Size; z += 1)
{
VisitedCells[x, z] = false;
}
}
var movement = new List<Stack<Vector2>>();
var CLoci = new Vector2(((int)(transform.position.x) - ((int)transform.position.x % 5)) / 10, ((int)(transform.position.z) - ((int)transform.position.z % 5)) / 10);
movement.Add(new Stack<Vector2>());
movement[0].Push(CLoci);
PathFinder(movement, grid, PLoci, VisitedCells);
for (int x = 0; x < movement.Count; x += 1)
{
Debug.Log(movement[x].Peek());
}
Alert = false;
}
}
}
Comment