Prevent the continuous looping of tree generation using Breadth-First Search (

My current assignment involves writing a program to determine the shortest path between a knight and a target tile on a chessboard. The task requires me to represent the knight's possible moves in a tree structure and utilize recursion to find paths to the target location. I've encountered challenges with the recursive call in the `getMoves` function, particularly regarding avoiding repeating visited tiles to prevent an infinite loop.

While browsing solutions on StackOverflow, I noticed various methods involving graphs and simpler implementations. However, I have opted to use trees and Breadth-First Search (BFS) as the primary approach due to my ongoing study focus and the specific requirement of this exercise. The code consists of three classes: `Board`, `Knight`, and `TreeMoves` where the available moves are stored. The BFS algorithm resides within the `TreeMoves`, iterating through each tree level recursively to check for a node matching the target position. Essentially, the process entails generating all possible knight moves, running BFS to identify the target location, and recursively expanding the tree to explore further positions, excluding previously visited ones.

Although I considered creating a more concise version for the community, I'm concerned it might cause confusion at this point. The existing code performs well when the target is within immediate reach of the knight's available moves. However, if the target is slightly moved away from these initial positions, it leads to the infinite loop issue mentioned earlier.

I would appreciate any guidance or hints on identifying potential mistakes in my implementation.

Cheers!


        <!-- JavaScript code snippets omitted for conciseness -->
    

Answer №1

After persistent efforts, I successfully resolved the structural issues in my code by relocating the getMoves method to the MovesTree class and making some necessary corrections. Utilizing the BFS algorithm played a crucial role in managing move generation effectively, preventing infinite loops. Surprisingly, implementing this method not only prevented unexpected behavior but also unveiled that the shortest path consists of a series of moves elucidated wonderfully in this question: Knight's Shortest Path on Chessboard, if my memory serves me right. Without further ado, here is the finalized code.

  static size = 8;

  targetPos = [];
  targetToken = 't';
  moveToken = 'a';

  static isOutOfBoundaries(x,y){
    if(x>Board.size-1||x<0)
      return true;
    else if(y>Board.size-1||y<0)
      return true;
    else
      return false;
  }

  constructor(){
    this.tiles = Array.from(Array(Board.size), ()=>Array.from(Array(Board.size), tile=>'·')); 
  }

  visualize(){
    this.tiles.forEach(row=>console.log(row.join(' ')));
  }

  placeItem(position, token){
    if(Board.isOutOfBoundaries(position[0],position[1]))
      throw new Error(`Piece/Target is out board boundaries`);
    else
      this.tiles[position[1]][position[0]] = token;
  }
  
  markPieceMoves(piece){
    for(let i = 0; i<piece.moves.length; ++i)
      this.tiles[piece.moves[i][1]][piece.moves[i][0]] = this.moveToken;
  }

}

class MovesTree{
  constructor(position){
    
    this.pos = position;


    // Initialization of move directions


  }

  static getMoves(node){
    const twoSteps = 2;
    const oneStep = 1;
    // Move generation logic

    
  }    

  BFS(func,target){
    let queue = [this];
    while(queue.length>0){
      if(target.toString()!==queue[0].pos.toString()){
        MovesTree.getMoves(queue[0])
        queue.push(...func(queue[0]));
      }
      else
        return; 
      queue.shift();
    }
  }

  DFS(node, target, path){

    let visited; 
    path === undefined ? visited = [node.pos]: visited = this.mergePath(path, node.pos);
    if(node.pos.toString()===target.toString()){
      visited.reverse();
      console.log(visited);
      return;
    }
    else{
      // Depth First Search traversal

    }
  }

  toArray(node){

    // Convert tree nodes to array
    
  }

  mergePath(path, current){
    let merged = [];
    merged.push(current);
    path.forEach(step=>{
      merged.push(step)
    });
    return merged;
  }
}
class Knight{
  token = 'k';
  constructor(row,col){
    this.position = [row,col];
    this.moves = new MovesTree(this.position,this);
  }
}
const board = new Board();
board.targetPos = [6,0];
const knight = new Knight(0,7);
board.placeItem(knight.position, knight.token);
board.placeItem(board.targetPos, board.targetToken)

knight.moves.BFS(knight.moves.toArray, board.targetPos);
knight.moves.DFS(knight.moves, board.targetPos)
board.visualize();

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

Display HTML components as JSON data using AngularJS

Recently, I started exploring angular js and faced a challenge in formatting json data with the help of angular js. Below is a snippet of my json data: [ {"field_add_link": "<a href=\"/drupal3/drupal3/\">Home</a>"}, {"field ...

Having trouble with my basic AJAX request; it's not functioning as expected

I am currently diving into the world of Ajax and I've hit a roadblock: 1. HTML : <body> <form> Username: <input type="text" id="username" name="username"/> <input type="submit" id="submit" /> </form> <scrip ...

The type 'Pagination<UserEntity>' is lacking the following attributes from type 'UserEntity':

I have set up pagination using the library found at https://github.com/nestjsx/nestjs-typeorm-paginate. However, I am encountering an error with the code snippet below: return this.usersService.findAll({ page, limit }); Can anyone offer insight into wha ...

Troubleshooting a Laravel method invoked in JavaScript using PhpStorm

I'm seeking some advice on how to debug a Laravel function mapped in a JavaScript function that is being called in an HTML page. $('#upload-avatar').fileapi({ url: '{{ route("user.avatar") }}', accept: 'image/*&a ...

Kudos to the information provided in the table!

My JSON data is structured like this: { description : "Meeting Description" name : "Meeting name" owner : { name: "Creator Name", email: "Creator Name" } } I want to present the details in a table format as follows: Meeti ...

Error: Unable to locate module: Issue discovering 'crypto' and 'fs' modules

I am currently in the process of learning React and attempting to establish a connection between my React app and my database using the following code: var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: ...

problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet: const response = await fetch(' ...

In main.js within the Google Maps API, an error is triggered when trying to setDraggable(false) on a

Here's a piece of JavaScript code I'm working with: google.maps.event.addListener(mark, 'dragend',x(mark)); function x(mark) { mark.setDraggable(false); } Recently, when I try to move a marker to a different position, I encounter ...

Error: Unable to submit form with jQuery due to timeout issue - e[h] function not recognized

This question has surfaced on SO previously without any solution, maybe due to a different scenario Below is the form in question <form id="testSubmit" method="post" action="submit.php"> <!--The value of the following field will be collecte ...

Error Encountered: Angular JS Throwing Unhandled Injection Error

I am having trouble validating the fields in my index.html and js files. I keep seeing errors, even after trying different versions of angular-route.min.js and angular.js. AngularJs | Basic Login Form <body ng-app="myApp"> ...

What is the best way to cycle through sprite positions within an array?

Having a string array containing the sprites to display: var lts = [ "letterA", "letterB", "letterC", "letterD", "letterE", "letterF" ]; These sprites are loaded in assets.js: function loadAssets(callback){ function loadSpri ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...

aviary usage resulted in a file_get_contents error

I successfully integrated aviary into my webpage and it's functioning properly. However, I'm encountering an issue with using the file_get_contents command to retrieve the saved image. Here's the aviary code: JS: <!-- Load Feather code ...

After clicking on the checkbox, req.body.task becomes undefined

Whenever I click on the checkbox, the value of req.body.task returns as undefined. <input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})"> This function is triggered by a change event on the checkbox and it ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Comparison between using jQuery to append and execute a <script> tag versus using vanilla JavaScript

As I enhance my application, I've made the decision to embrace Bootstrap 5, which no longer relies on jQuery. Consequently, I am working to eliminate this dependency from my application entirely. One of the changes I'm making is rewriting the Ja ...

encountering a typeError upon attempting deployment on Heroku

This is my first project using node.js, so my code may not be perfect It runs smoothly on my localhost, but on Heroku, I encounter an 'Internal Server Error' along with a TypeError. I apologize for my limited knowledge of node.js and ejs, but I ...

Is it better to deploy a JS app to the browser, or should I consider using nw.js

Is there a tool available for developing a javascript application that can be deployed as either a browser-based or native app using nwjs or Atom Electron? It should only utilize browser-compatible features and not node's native features. Maybe th ...

Tips for updating a specific portion of a component in react.js

import React,{useEffect} from 'react'; import CloudTables from '@cloudtables/react'; import { useState } from 'react'; function DataGridTable ({ input1Value, input2Value }) { return ( <div className="con ...