After implementing a dfs search for an 8 puzzle game, I have encountered an issue where my stack keeps adding possible movements without decreasing to find an answer. It seems like the code is not working correctly as a dfs should be, and I'm seeking help in identifying the problem.
Although the code is not fully optimized, I am unsure why it is failing to work properly as intended for a depth-first search. Any assistance would be greatly appreciated, 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);
}
}
}