简体   繁体   中英

How to calculate shortest possible route between nodes?

I have the following variable input array to my program, for example: [AB3, EC10]

It can be any length, and the first-second characters are origin and destination of a route, respectively. The number following is the distance between the first and second characters (the nodes).

How would I go about calculating the shortest possible route from one point to another, if you can only advance from one node to another by steps (to go from A to D, you would have to go AB, BC, CD, ED) and the distance is variable between the nodes?

const routesInfo = ["AB5", "BC4", "CD8", "DC8", "DE6", "AD5", "CE2", "EB3", "AE7"]

  const stop1 = 'A',
  stop2 = 'B',
  stop3 = 'C',
  stop4 = '',
  stop5 = ''

  var trip1dist = 0,
    trip2dist = 0,
    trip3dist = 0,
    trip4dist = 0,
    dist = 0

  // for 3 stations
  if (stop1 && stop2 && stop3 && (!stop4) && (!stop5)) {
    var foundFirst = false,
    foundSecond = false
    for (var i = 0; i<routesInfo.length;i++) {
      var origin = routesInfo[i].charAt(0),
      destination = routesInfo[i].charAt(1)
      if (origin == stop1 && destination == stop2) {
        distance = routesInfo[i].charAt(2)
        trip1dist = distance
        foundFirst = true
      }
      if (origin == stop2 && destination == stop3) {
        distance = routesInfo[i].charAt(2)
        trip2dist = distance
        foundSecond = true
      }
    }
    // REFACTOR CHECKING FOR IMPOSSIBLE ROUTE
    if (foundFirst && !foundSecond) {
      console.log(null)
    }
    if (!foundFirst && foundSecond) {
      console.log(null)
    }
    if (!foundFirst && !foundSecond) {
      console.log(null)
    }
    var total = Number(trip1dist) + Number(trip2dist)
    console.log('The distance of the trip was: '+total)
  }

If you know the start and end points beforehand, you could run Dijkstra's algorithm to find the shortest path between the start and end point. Dijkstra's algorithm is a well-known solution for the shortest path problem in a graph. You can read more about it here . Also, you can find implementations of it quite easily.

If you want to know the shortest distance between any two given points, you should take a look into the Floyd-Warshall algorithm. You can read more about it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM