Search Unity

Maze generator using DFS algorithm not working

Discussion in 'Scripting' started by monschraktor, Aug 8, 2020.

  1. monschraktor

    monschraktor

    Joined:
    May 31, 2020
    Posts:
    2
    I am trying to make a maze generator using DFS algorithm.
    Below is my code.
    https://github.com/mocha4coding/Maze/blob/master/MazeGenerator.cs
    In the StartAlgorithm method, whenever the currentCell has no univisted neighbor, the neighbors.Count should be zero. Therefore neighbors.Count > 0 will be false and it should enter the else part.
    But for some reason, neighbors.Count is never zero, and rather contains points to the very first grid(The one with gridPos = 0,0)[SCREENSHOT ATTACHED]
    Can someone tell me the reason why?
    (I am more of a C++ coder and still a noob about C#. Any sort of help is appreciated. )
    (The DFS implementation might appear weird because i am pushing elements twice, but it works, I saw it somewhere on leetcode and works everytime.)
     

    Attached Files:

  2. Elango

    Elango

    Joined:
    Jan 27, 2016
    Posts:
    107
    It looks like a problem in GetUnvisitedNeighbor logic.
    You create a new instance (which will have position (0,0) by default)
    Cell neighbor = new Cell();

    and then add it to the list of possible neighbors even if the #_adjacent cell fails the test for presence in the grid ((4,1) for example)
    neighborsList.Add (neighbor);

    and checking it only for the fact that it is not present in the visited list. Of course it won't be there.
    Try putting a second IF block inside the first for each adjacent check.
     
    Last edited: Aug 8, 2020
    eisenpony likes this.
  3. monschraktor

    monschraktor

    Joined:
    May 31, 2020
    Posts:
    2
    @Elango Thanks a lot!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! My code is working properly now!!!!!!!!!!!!!!!!!!
     
    eisenpony likes this.