Dijkstra's algorithm

Dijkstra's algorithm is a greedy algorithm (you will learn more about greedy algorithms in Chapter 14, Algorithm Design and Techniques) to calculate the shortest path between a single source and all the other sources, meaning we can use it to calculate the shortest path from a graph vertex to all the other vertices.

Consider the following graph:

Let's take a look at how we can find the shortest path between the vertex A and all the other vertices. But first, we need to declare the adjacent matrix that represents the preceding graph, as follows:

var graph = [[0, 2, 4, 0, 0, 0], [0, 0, 1, 4, 2, 0], [0, 0, 0, 0, 3, 0], [0, ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.