What algorithm can I use to find the shortest path between specified node types in a graph?

后端 未结 8 1849
自闭症患者
自闭症患者 2021-02-14 12:19

This is the problem:

I have n points (p1, p2, p3, .. pn), each of them can connect to any other with a determined cost x.

Each point belongs to one of a set of p

相关标签:
8条回答
  • 2021-02-14 12:31

    There are many algorithms that will do better than calculating all the possible paths. Breadth-first search is the basic starting point for the family of algorithms I have in mind, Best-first search is appropriate because you have vertex costs defined, and if you can get more information about your problem space, you may be able to use A* or Dijkstra's algorithm. (In each case, finding the paths from the set of allowed starting nodes.)

    Re your edit: Your path constraint (the array of node types you need to satisfy) doesn't prevent you from working with these algorithms; quite the opposite, it helps them all work better. You just need to implement them in a way that allows the path constraint to be incorporated, limiting the vertices available at each step in the search to those that are valid given the constraint.

    0 讨论(0)
  • 2021-02-14 12:44

    Here is pseudocode with dynamic programming solution:

    n - length of desired path
    m - number of vertices
    types[n] // desired type of ith node
    vertice_types[m]
    d[n][m] // our DP tab initially filled with infinities
    
    d[0][0..m] = 0
    for length from 1 to n 
      for b from 0 to m
        if types[length] == vertice_types[b]
          for a from 0 to m
            if types[length-1] == vertice_types[a]
              d[length][b] = min(d[length][b], d[length-1][a] + cost(a,b))
    

    your minimum cost path is min(d[n][0..m])

    you can reduce size of d table to 2 rows, but it would obfuscate the solution

    0 讨论(0)
提交回复
热议问题