Utilizing recursive backtracking to determine a route from the starting point to the end point within a two-dimensional array

I am attempting to navigate a 2D array from a starting point (x,y) to a destination point (destX, destY).

My approach involves utilizing backtracking recursion to find any possible path instead of focusing on the shortest one.

However, I have encountered an issue where the algorithm seems to get trapped in a corner, indicating a flaw in my logic somewhere.

Here is the recursive function:

$scope.findPath = function(x, y, destX, destY) {
        console.log("x: " + x + ", y: " + y);
        if(x >= $scope.buttons.length || x < 0 || y >= $scope.buttons[0].length || y < 0) {
            return false;
        }

        if(x == destX && y == destY) {
            return true;
        }

        if(!$scope.checkIfButtonEmpty(x, y)) {
            console.log("location not empty")
            return false;
        }

        $scope.solution[x][y].marked = true;

        if($scope.findPath(x + 1, y, destX, destY) === true) {
            return true;
        }
        if($scope.findPath(x, y + 1, destX, destY) === true) {
            return true;
        }
        if($scope.findPath(x - 1, y, destX, destY) === true) {
            return true;
        }
        if($scope.findPath(x, y - 1 , destX, destY) === true) {
            return true;
        }

        $scope.solution[x][y].marked = false;

        return false;
    };

The following function initiates the recursion and once a path is found and stored in a boolean 2D array, it is meant to visually display the path:

$scope.startDrawingConnection = function() {
        if($scope.startLocation.length == 2 && $scope.endLocation.length == 2){
            $scope.findPath($scope.startLocation[0], $scope.startLocation[1], $scope.endLocation[0], $scope.endLocation[1]);
            console.log("Finished finding path");
            $scope.drawPath();
            console.log("Finished drawing path");
        }
    };

I am seeking assistance in identifying the error in my algorithm. Any help would be greatly appreciated.

Answer №1

The issue arises when you find yourself stuck in a cycle, repeatedly revisiting nodes that have already been explored without success and attempting them again.

It is crucial for the search algorithm to avoid revisiting the same square more than once. To accomplish this, track your previous locations in a manner that preserves the path while backtracking, preventing re-exploration of those squares.

To implement this, consider adding an extra property to your solution nodes and insert the following code snippet just before marking a node as marked = true:

    if ($scope.solution[x][y].visited) return false;
    $scope.solution[x][y].visited = true;

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

At what point can we rely on the accuracy and timeliness of Element.getBoundingClientRect?

I am currently in the process of developing some code that utilizes Element.getBoundingClientRect (gBCR), combined with inline style updates, to carry out calculations. This particular project is not intended for a general website, so I am not interested i ...

Retrieve the content entered in a form text field without needing to officially submit the form

Is it possible to submit the text box value (partnumber) as a query string in a hyperlink without submitting the form itself? I have been trying to achieve this by using document.getElementById("partnumber").value but keep getting an error "Object Required ...

Characteristics of JSON data containing quotation marks within the property values

Is it possible to include JavaScript functions in JSON like the example below? My JSON library is struggling to process this structure because of the quotations. How can I address this issue? I specifically need to store JavaScript functions within my JSON ...

Advantages and Disadvantages of Implementing Ajax for Form Validation

Exploring the benefits of validating forms with Ajax, I find it to be a valuable tool in preventing code redundancy. However, before making the switch, I am curious about any potential drawbacks compared to traditional JavaScript validation. While I have c ...

Using MutationObserver in an iFrame with JavaScript

I currently have an iframe that is loaded with the source www.abc/main.html <iframe id="my-iframe" src="http://www.abc/main.html"></iframe> The main.html file from abc imports and runs some JavaScript files. My goal is to utilize a MutationO ...

Tips for concealing a tooltip once a checkbox becomes enabled

I want to show a tooltip only when a checkbox is disabled. Once the correct format is typed into an input text field, the checkbox should become enabled. Currently, I am able to display the tooltip when the checkbox is disabled, but it does not hide when ...

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

What steps can be taken to resolve the issue of the Cannot POST /index.html error?

Here is an example of a calculator app created using HTML and Javascript. Upon running the program with nodemon and accessing localhost:3000, pressing the submit button triggers an error on Google Chrome. [nodemon] starting `node calculator.js` Server sta ...

Socket IO: Error - The call stack has exceeded the maximum size limit

Whenever a client connects to my node.js server, it crashes with a 'RangeError: Maximum call stack size exceeded' error. I suspect there's a recursive problem somewhere in my code that I can't seem to find. This is the code on my serve ...

Guide for converting innerHTML text within an Angular JS controller

Hey! I'm currently working on a Angular JS web application that supports two languages: English and Italian. So far, I've managed to translate all the text from my HTML page like this: {{translation.ERROR_12}} Now, I need to pass some text from ...

Utilize $or or $and for incorporating multiple conditions in a match statement

I've seen this question posted before, but I'm having trouble locating the answer. I want to filter shows with flag 1 and flag 2 using $or for searching. How can I include a condition for flag 2 along with flag 1 in my code? Currently, I only ha ...

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

Eslint in VS Code encounters issues resolving paths within a monorepo

I'm currently working on a project with the following structure: modules │ ├── client │ ├── .eslintrc.json │ └── backend │ ├── .eslintrc.json ... One issue I've run into is that when I access the p ...

The dimensions of the div do not match the size of the image

I am struggling to adjust the color of a transparent image within a div using jQuery. I am facing difficulties in keeping the image aligned within the div while changing its color. Can someone provide assistance? My goal is to have the image filled upon a ...

Using Angular to create HTTP routes in conjunction with Node.js

My current challenge involves trying to access a .json file that contains my portfolio. I have set up my backend using express js, and am attempting to retrieve the data using angular in the following manner: $http.get("data/items.json") .success(function ...

Tips for incorporating debounce functionality into typeahead.js

I am currently developing a search functionality using typeahead.js. I am facing the challenge of implementing debounce for the search feature. Despite my efforts to refer to the typeahead documentation, I have not been able to find any useful informatio ...

Is there a way to clear the list after each input is made?

Looking for help with the Ping Pong Test. Whenever I click Start and enter a number, it just keeps adding to the list. How can I make it reset the list after each input? $(document).ready(function() { $("#Start").click(function() { ...

"Transforming a PHP array into a well-structured string format

If I have an array structured like the one below, which could be multi-dimensional, I need to implement a recursive loop to properly handle it. I believe I am almost there, but I am struggling to identify the mistake in my code. [ { "value": "ri ...

What could be causing my textarea-filling function to only be successful on the initial attempt?

Programming: function updateText() { $("body").on("click", ".update_text", function(event) { $(this).closest("form").find("textarea").text("updated text"); event.preventDefault(); }); } $(document).ready(function() { updateText(); }); H ...

Redirecting with Express js when the cookie is not found

I successfully integrated Facebook login using Passport-js and also set up Cookie-strategy for traditional username/password login on my Express-js backend with a React front-end. The backend and frontend are hosted on separate servers and domains (backend ...