简体   繁体   中英

Is there a function that finds the shortest path between two nodes?

Using python, is there a function that allows me to find the shortest distance between two nodes in a networkx graph. The function itself cant be from networkx. Essentially what im asking, is there an alternative function for networkx.shortest_path_length() without actually using NetworkX. I've looked at the source code and it also has nx functions.

Yes there is, Dijkstra's algorithm . The algorithm creates a tree of shortest paths from the starting vertex, the source, to all other points in the graph.

def dijkstra(self, src): 

    dist = [sys.maxint] * self.V 
    dist[src] = 0
    sptSet = [False] * self.V 

    for cout in range(self.V): 
        u = self.minDistance(dist, sptSet) 
        sptSet[u] = True

        for v in range(self.V): 
            if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]: 
                    dist[v] = dist[u] + self.graph[u][v] 

    self.printSolution(dist) 

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