Complexity | Note | |
---|---|---|
Worst Time: | O(V + E) | Where V is the number of vertices and E is the number of edges |
Worst Space: | O(V + E) | Assuming an Adjacency List is used |
An algorithm to traverse (or specifically search for) nodes in an unweighted graph. The basic idea is to traverse every node by placing any newfound nodes into a queue to be traversed through.
- Initialise a list called
Discovered
and insert the starting nodeA
with distance0
- Initialise a list called
Finalised
- While
Discovered
is not empty:- Get the first vertex
V
from theDiscovered
list - For each adjacent vertex
U
ofV
:- If
U
is not discovered or finalised:- Set the distance of
U
to the distance ofV
+1
- Insert
U
at the end ofDiscovered
- Set the distance of
- If
- Move
V
fromDiscovered
toFinalised
- Get the first vertex