Is Dijkstra's algorithm for directed or undirected graphs?

It can be applied to both. Here is why:

An undirected graph is basically the same as a directed graph with bidirectional connections (= two connections in opposite directions) between the connected nodes.

So you don't really have to do anything to make it work for an undirected graph. You only need to know all of the nodes that can be reached from every given node through e.g. an adjacency list.


You can use Dijkstra's algorithm in both directed and undirected graphs, because you simply add edges nodes into the PriorityQueue when you have an edge to travel to from your adjacency list. For example, if one of my nodes has an edge from A to B of weight 3, then if it's directed from B I won't be able to add the edge back into A, while from A I could add it to B.

Like the other answers, make sure you do not confuse it with weights. Dijkstra's algorithm runs on positive weighed graphs, otherwise the priority queue would be useless.

In your example, Dijkstra's algorithm would work because the graph is both weighed (positively) and has directed edges.

The fault would have been that the edges have been double-assigned in the form of an undirected graph. You should be careful when parsing the edges at the beginning into your objects to not duplicate the edges in the adjacency list.


A graph being directed just means that the edges connecting vertices are able to connect one way, but not the other. This means that one vertex can be adjacent to another, but that other vertex may not be adjacent to the first vertex.

In the context of Dijkstra's algorithm, whether the graph is directed or undirected does not matter. Dijkstra's algorithm simply references the adjacent vertices of a vertex. It is this adjacency list that you would have to modify if you were changing a graph from directed to undirected.