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

后端 未结 8 2041
自闭症患者
自闭症患者 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: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

提交回复
热议问题