Is there an issue with the way I've implemented my depth-first search algorithm?

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);
}
}
}

Answer №1

After some consideration, it became clear to me that the sheer number of combinations when traversing my graph in depth could potentially lead to an infinite or unmanageable amount. Realizing this, I made the decision to implement an iterative Depth-First Search (DFS) approach which explores each child node by levels rather than continuing indefinitely in a single direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Correct the string based on a character error

When I have text to display in HTML, for example: var htmlStr = "1.first thing %10-15%. 2.second thing %25-44%. 3.third" And I want to display it in a div: $('#div1').html(htmlStr); However, when I display it in a DIV1 in HTML5 on a mobile pho ...

Activate background functionality while modal is active in Bootstrap 4

I have come across similar questions addressing the need to change the following: .modal-backdrop { display: none; } However, my modal does not have this .modal-backdrop. I am unsure if this is a new feature in Bootstrap 4, but the mentioned solution ...

Generate a selection of complementary, triadic, and monochromatic color palettes using just one hex color code

My goal is to generate three unique color palettes based on a single hex/rgb value given by the user. The first palette will feature the complementary color of the initial input, followed by a full range of colors in subsequent palettes. I aim to expand be ...

What is the best way to retrieve data from the previous webpage and navigate it to the appropriate page using HTML?

I have a pair of HTML files known as list.html and detail.html. From https://jsonplaceholder.typicode.com/posts, I am retrieving title and body data to exhibit on a posts.html page in the following format: posts.html output Displayed below is my posts.ht ...

Organize and eliminate items within a vessel

Looking to manipulate a container with span elements by removing two and re-arranging one. I attempted the following approach: $('span.class5').insertBefore('span.class0'); However, this inserted each span.class5 into every repeating ...

I'm absolutely obsessed with it: Error - unable to switch to an abstract state

Hey there! Currently, I'm working on an app using the IONIC Framework and running into some issues with user validation errors. Below, you'll find a snippet of the logic I've implemented: app.js: angular.module('skulApp', [' ...

Access-Control-Allow-Origin does not permit AngularJS Origin http://localhost:8080

I'm working on a web application using AngularJS. It's an admin interface that depends on a json-rpc API hosted on a different domain. When testing in my local environment, I encountered the error "Origin http://localhost:8080 is not allowed by ...

Using soapUI to extract information from a JSON Response with arrays

After receiving a JSON response from a previous test step in soapUI, I am working on parsing the information using a groovy script. Here's a snippet of the JSON response: { "AccountClosed": false, "AccountId": 86270, "AccountNumber": "2915", ...

What is the process for translating symbols in a URL or text into hexadecimal characters? (e.g. changing = to %3D)

Currently, my script in use is extracting variables from URL parameters using jQuery. The value it retrieves happens to be a URL. For instance, if the URL is as follows: http://localhost/index.html?url=http://www.example.com/index.php?something=some the ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

What is preventing my counter from functioning when I click on the canvas?

I am attempting to increment the count every time a bouncing ball in the browser is clicked using this.setState({count: this.state.count + 1});. I thought my code was correct since I have done similar tasks before without using canvas, but it's not fu ...

Mastering the art of dynamically chaining methods in JavaScript

I am in search of a method to dynamically chain different populate methods for various paths in a Mongoose document. The goal is to efficiently retrieve all necessary fields at once. Below is the current code snippet: let fields = [path1, path2, ...] let ...

Difficulty implementing clickable dropdown buttons in a React navbar

After some tweaking, I was able to create buttons that trigger dropdown menus which disappear when clicked off. However, a problem arises when any button is clicked - all of the dropdowns appear at once. It appears that setting the state for one button a ...

When working with arrays in a programming loop, is it better to assign the value to a variable or access it directly?

When facing a complex for loop with lots of operations, what is the most efficient way to iterate through it? for ($i = 0; count($array) > $i; $i++) { $variable = $array[$i]; $price = $variable->price; OR $price = $array[$i]->price; } T ...

Launching an Electron Window and Recording the Closing Event

I am currently developing a Desktop Application using Electron. I want to implement a feature where clicking on a button in the main window (index.html) will open a different window. After researching, I discovered the BrowserWindow from the Electron API. ...

Utilizing Angular 9 with Jest for unit testing: simulating a promise, checking for method invocation afterwards

I'm in need of assistance as I am unsure how to mock a promise and verify that a method is called within the then() block. When I click on the save button of my form, my code appears as follows: // File: myComponent.ts save() { const myObject = n ...

Incorporating a flexible header size and scrollable content: Tips for avoiding the need to scroll through the entire page to find

I am currently working on creating a unique page template that has certain requirements: The height of the header may vary The content and aside containers should be independently scrollable Anchor links should not disrupt the page layout To see what I h ...

Disable the ability for new windows, such as popups, submit buttons, and forms with the target set to blank, to reference

Encountering an issue, I stumbled upon some solutions here and on various other websites that I would like to share with you. The Problem: The window.opener functions of child pages stopped working after some security updates in modern browsers around 202 ...

Python implementation of dynamic N-dimensional finite difference computation along a specific axis

I am working on a function that calculates the finite difference of a 1d np.array and I am looking to expand it to work with n-dimensional arrays. The current function looks like this: def fpp_fourth_order_term(U): """Calculates the second derivative ...

Ways to eliminate an object from an array using Javascript or Jquery

I have two arrays of objects (with the same properties) where I need to remove all objects with the same name as those found in filesToRemove from the array files. However, when I attempt to use the code below, it throws an error: Uncaught TypeError: fil ...