Python 在图形项的依赖项列表中向上的最短路径

Python 在图形项的依赖项列表中向上的最短路径,python,algorithm,graph,Python,Algorithm,Graph,如果我有此数据结构: {'id': {0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7', 7: '8'}, 'parents': {0: [], 1: ['1'], 2: ['1'], 3: ['3'], 4: ['3'], 5: ['5', '4'], 6: ['3', '2'], 7: ['7', '6', '5', '2']}} mypd=pd.DataFrame.from_dict(mydata)

如果我有此数据结构:

{'id': {0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7', 7: '8'},
'parents': {0: [],
  1: ['1'],
  2: ['1'],
  3: ['3'],
  4: ['3'],
  5: ['5', '4'],
  6: ['3', '2'],
  7: ['7', '6', '5', '2']}}
mypd=pd.DataFrame.from_dict(mydata)
导致:

该表显示了依赖项。每个实体都依赖于一些更高层次的实体,这些实体也依赖于更高层次的实体。所有依赖项都以这样或那样的方式以1结尾

我正在寻找一个算法,以找到最短的路径,从每个项目到1。 例如,项目8依赖于2,因此可能仅通过两次跳转到达一个。 最短的路径是2,1

我猜我需要一个递归函数,它递归地获取每个父级列表中的最大数。 但我不知道如何实现这一点


这个问题也可以看作是从1到其他任何一个项目的最短路径。

Dijkstra说:

Link Costs, a generic path finder
l 2 1 1
l 3 1 1
l 4 3 1
l 5 3 1
l 6 5 1
l 6 4 1
l 7 3 1
l 7 2 1
l 8 7 1
l 8 6 1
l 8 5 1
l 8 2 1
 
2 -> 1 ->


3 -> 1 ->


4 -> 3 -> 1 ->


5 -> 3 -> 1 ->


6 -> 8 -> 2 -> 1 ->


7 -> 3 -> 1 ->


8 -> 2 -> 1 ->
这方面的C++代码:

#包括“cPathFinder.h”
main(int argc,char*argv[])
{
//自我介绍

std::cout这里是一个纯python解决方案,用于在隐式假设路径是单向的情况下查找最短路径。 它首先生成所有可能的路径,然后选择最短路径。如果存在多条最短路径,则返回包含所有路径的列表

parents = {
    '1' : [],
    '2' : ['1'],
    '3' : ['1'],
    '4' : ['3'],
    '5' : ['3'],
    '6' : ['5', '4'],
    '7' : ['3', '2'],
    '8' : ['7', '6', '5', '2'],   
}

def shortestPath(item):

    item = str(item) # because numbers are given as str in the example
    allPathsList = []

    def allPaths(item, path = []):
        nonlocal allPathsList
        path.append(item)

        if len(parents[item]) == 0:
            allPathsList.append(path) # apend path to list when end reached
        elif len(parents[item]) == 1:
            allPaths(parents[item][0], path) # for single parent proceed along path
        else:
            for parent in parents[item]:
                allPaths(parent, list(path)) # create bifurcations for multiple parents

    allPaths(item)

    minLength = len(parents) # amound of items should be longest possible path
    for path in allPathsList:
        minLength = min(minLength, len(path)) # look if shorter ones exist

    # retrieve all paths having minLength
    returnList = [path for path in allPathsList if len(path) == minLength]
    if len(returnList) == 1: # if a distinct shortest path exists, return only this one
        return returnList[0]
    return returnList # otherwise return list of alternatives

shortestPath(8)
> ['8', '2', '1']

Dijkstra算法你需要最短路径长度还是最短路径本身?如果是后者,那么对多条最短路径有约束吗?当有多条最短路径时,所有最短路径都有约束