Algorithm -- dixtra algorithm

Posted by damiantaylor on Mon, 04 Nov 2019 21:28:00 +0100

Dixstra algorithm

Algorithm -- dixtra algorithm

Dijkstra's algorithm: find the fastest path, not the path with the least number of segments.

The dixstral algorithm is used for graphs where each edge has associated numbers, which are called weights.
A graph with weight is called a weighted graph, and a graph without weight is called an unweighted graph.
The breadth first search can be used to calculate the unweighted graph, and the dixtra algorithm can be used to calculate the weighted graph.
The dixtra algorithm is only suitable for directed acyclic graph (DAG).
If there is a negative weight edge, we can't use the dirkstra algorithm, but use the bellman Ford algorithm.

Steps:
1) find out the point that can be reached in the shortest time
2) the cost of updating the neighbor of the node
3) repeat this process until all nodes in the figure have been done
4) calculate the final path

Main points:
Breadth first search for shortest path in unweighted graph
Dixtra algorithm for finding the shortest path in weighted graph
The dixtra algorithm works only when the weight is positive
If the graph contains negative weight edges, use the Berman Ford algorithm
# dijkstra Dixstra algorithm


def find_lowest_cost_node(costs):
    lowest_cost = float('inf')
    lowest_cost_node = None
    for node in costs:
        cost = costs[node]
        if cost < lowest_cost and node not in processed:
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node


if __name__ == '__main__':
    graph = {}
    graph['start'] = {}
    graph['start']['a'] = 6
    graph['start']['b'] = 2
    graph['a'] = {}
    graph['a']['fin'] = 1
    graph['b'] = {}
    graph['b']['a'] = 3
    graph['b']['fin'] = 5
    graph['fin'] = {}

    infinity = float('inf')
    costs = {}
    costs['a'] = 6
    costs['b'] = 2
    costs['fin'] = infinity

    parents = {}
    parents['a'] = 'start'
    parents['b'] = 'start'
    parents['fin'] = None

    processed = []

    node = find_lowest_cost_node(costs)  # Find the least expensive node among the unprocessed nodes
    while node is not None:  # this while Loop ends after all nodes have been processed
        print(node)
        cost = costs[node]
        neighbors = graph[node]
        for n in neighbors.keys():  # Traverse all the neighbors of the current node
            new_cost = cost + neighbors[n]
            if costs[n] > new_cost:
                costs[n] = new_cost
                parents[n] = node
        processed.append(node)
        node = find_lowest_cost_node(costs)

Topics: PHP