0

I have implemented a dfs search for an 8 puzzle game but for some reason I can't manage to get it work as it should, my stack keeps adding and adding possible movements for my 8 puzzle game but it never decreases for an answer, I don't know if it is normal or not but here is my code in case someone can help me.

The code is not fully optimized I know, I just want to know why it is not working as a dfs should be, thank you.

function depthFirstSearch(currentState, finalState)
{
  var stack = [];
  var visited = [];
  delete currentState["prev"];
  stack.push(currentState);
  while(stack.length)
  {
    var node = stack.pop();
    visited.push(node);
    if(compare(node, finalState))
    {
      return visited;
    }
    else
    {
      var successors = getSuccessors(node);
      for(var i = 0; i < successors.length; i++)
      {
        delete successors[i]["prev"];
      }
      var realSuccessors = [];
      for(var i = 0; i < visited.length; i++)
      {
        for(var j = 0; j < successors.length; j++)
        {
          if(compare(successors[j], visited[i]))
          {
            continue;
          }
          else
          {
            realSuccessors.push(successors[j]);
          }
        }
      }
      for(var i = 0; i < realSuccessors.length; i++)
      {
        stack.push(realSuccessors[i]);
      }
      console.log(stack.length);
    }
  }
}
Cande
  • 36
  • 7

1 Answers1

0

I'm going to answer myself since I realized that the number of combinations considering that im traversing my graph in depth could lead me to an infinite or long number of combinations and never reach the solution since I'm going just in one direction, therefore I thought about doing an iterative DFS which traverses each children by levels.

Cande
  • 36
  • 7