Navigating a complex web: Djikstra algorithm applied to a multigraph

Encountering an issue while implementing Dijkstra's algorithm on a multigraph. The graph consists of nodes representing stops with information and connections to other stops (edges). However, the challenge arises when there are multiple bus options between two nodes.

For example: Traveling from stop A to stop B can be done using bus 1, bus 2, bus 3, etc.

This results in finding a path that may not be optimal due to choosing an incorrect bus.

Another complication is having stops with the same name, but different directions.

The representation of my graph is as follows:

{
  ...,
  "5382778889": {
  "name": "Heroes Square",
  "coordinates": {
    "latitude": -25.9351311,
    "longitude": 32.5792925
  },
  "street": "Acordos de Lusaka Avenue",
  "connections": [
    {
      "stop": 6797387579,
      "bus": 10046632,
      "path": [...]
    },
    ...
  ],
    "walking_connections": [
    {
      "stop": "5382778890"
    }
  ]
  },
  ...
}

The implementation of my Dijkstra's algorithm is shown below:

findPaths(stops, startPoint, endPoint) {
  const distance = {};
  const queue = new PriorityQueue();
  const previous = {};
  const buses = {};
  const visited = new Set();

  for (const stop in stops) {
    distance[stop] = stop == startPoint ? 0 : Infinity;
    queue.enqueue(stop, distance[stop]);
  };
  
  while (!queue.isEmpty()) {
    const currentStop = Number(queue.dequeue());

    if (visited.has(currentStop)) {
      continue;
    };

    visited.add(currentStop);

    if (currentStop == endPoint) {
      const shortestPath = [];

      let stop = {
        stop: endPoint,
        name: stops[endPoint].name,
        coordinates: stops[endPoint].coordinates,
        street: stops[endPoint].street,
        path: [],
        bus: null,
      };

      ...
      
      return shortestPath;
    };

    if (stops[currentStop] && stops[currentStop].connections) {
      
      ...
      
      };
    };

    if (stops[currentStop].walking_connections) {
      
      ...
    
    };
  };
  
  ...
};

Answer №1

To enable a node to choose between different buses, the node should be split into multiple nodes, with free connections between them and one bus assigned to each node.

For example:

u -> via BusA -> v
u -> via BusB -> v

can be transformed into:

u1 -> u2
u1 -> via BusA -> v
u2 -> via BusB -> v

By implementing this approach, Dijkstra's algorithm will have no issues navigating through this graph, allowing for elimination of zero cost hops from the path.

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

Ensure the proper ordering of indexes in PHP arrays

Currently, I am exploring the most effective method to perform a specific test in PHP. The task involves analyzing a list of numbers and identifying any missing indices in the succession of these numbers. If there are missing indices, an alert needs to be ...

Enhance User Experience with Dynamic Scroll Page Transition

Hey everyone! I've been working on revamping a website and stumbled upon this fascinating page transition that I would love to replicate. However, I haven't been able to find a JQuery library that can achieve this effect. Does anyone have any i ...

Step-by-Step Guide for Attaching Table Legs

I believe that the four legs should be an integral part of the table, rather than just added on like an afterthought. What would be the best way to create new instances of legs and attach them in a way that makes the back legs look slightly smaller than t ...

Guarantee the successful execution of a server-side function using my client-side function

I am currently in the process of creating a website that utilizes Javascript and Asp.net. My code contains numerous functions on the client side, within my html code, while my server side functions are called using a webservice. How can I ensure that my c ...

Manipulating Object Properties in the Browser's Console

When I log a JavaScript object in the browser, my curiosity leads me to expand it in the console window. An example of this is: console.log(console); I discover what's inside, but then a thought crosses my mind. When I dig deeper and expand the obje ...

Exploring First-Person Shooter Rotation with THREE.JS

I recently attempted to create a rotation system for a First Person Shooter game using THREE.JS. However, I encountered a strange issue where the camera would pause momentarily before returning, especially at certain rotations. When checking the rotation ...

Determining the cursor location within a character in a div that is content editable using AngularJS

I am facing challenges with obtaining the cursor caret position within a contenteditable div. Currently, I am utilizing the following function : onBlurArea (field, ev) { ev.preventDefault() const editable = ev.target.childNodes[1].childNodes[2] ...

Adjusting the sensitivity of mousewheel and trackpad using JavaScript

I am currently utilizing CSS3 to smoothly move a div up and down based on the direction of scrolling. By monitoring the mouse wheel event, I can detect when a user scrolls down and trigger a CSS3 transition to slide the div up. However, I am encountering a ...

Using JavaScript to control the state of a button: enable or

In the process of creating a basic HTML application to collect customer information and store it in a database, I have encountered a specific user interface challenge. Once the user logs into their profile, they should see three buttons. Button 1 = Print ...

An advanced password checker that notifies the user of any spaces in their password

I need help fixing my JavaScript code. The program should prompt the user for a password using a dialogue box, and then validate that the input has no spaces. If a space is detected, the program should stop and display an alert saying "Invalid, contains a ...

Guide on adjusting the language settings for notifications in chosen.js?

Is it possible to customize the error message that appears in chosen.js when an unavailable option is typed into the multiple select box, which currently says 'No results match "query"'? ...

How can I show tab objects in a Chrome extension?

I'm currently working on developing a new Google Chrome extension that focuses on tab organization. Despite the abundance of similar extensions already available, I am determined to create my own unique solution. One idea I have is to create a popup w ...

Encountering a "Evaluation Failed" error while scraping YouTube data with Puppeteer and Node.js

As I attempt to scrape the YouTube headline and link from a channel using Puppeteer, I encounter an Evaluation Error presenting the following message: Error: Evaluation failed: TypeError: Cannot read properties of null (reading 'innerText') a ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

sending multiple checkbox selections to a PHP script using jQuery

<form id="foo"> <input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/> <input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/> <input type="text" name="voucher" placeholder="voucher ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

Transform an array containing arrays into an array of individual objects

After spending a considerable amount of time trying various solutions, I am still unable to achieve the desired result. The issue lies in getting an array of objects from service calls and organizing them into a single array for data loading purposes. The ...

Searching for the most recent entry from a related group within an HTML table using jQuery

I have a list of students in different classes that looks like this Class StudentName RollNo. Class X Sarah 1 Class Y David 2 Class Z Emily 3 Class W Adam 1 C ...

Error: ChunkLoadError encountered when trying to load the "blogs-component" chunk in Laravel Vuejs

Despite smooth functioning on local development, my Laravel + Vuejs project is encountering ChunkLoadError on 2 pages. After consulting similar cases on SO and confirming the file's existence in the output path, the issue persists. The affected page ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...