Graphs
Terminology
node
A point or vertice on the graph. (Also stated as V
)
edge
The connection between two nodes. (Also stated as E
)
connected
When every node has a path to another node.
cycle
acyclic
A graph that contains no cycles
.
directed
undirected
weighted
The edges have a weight associated with them.
dag
Directed, acyclic graph.
Representing Graphs
Adjacent List
A list, where each main index of the list points to a node of the graph, describing its connections to the other nodes.
This representation is more commonly used.
Traversing/Searching with BFS
BFS
Traversing/Searching with DFS
DFS
Easier to preserve the path
.
Runs on .
Adjacent Matrix
A matrix, where each main index of the first array points to a node of the graph, describing in a second array the weights to the other nodes or zero
if there is no connection.
Uses more memory, since it represents non-existent connections with zero
.
Traversing/Searching with BFS
BFS
Dijkstra's Shortest Path
An algorithm to find shortest path
, meaning find the edge
connections with smallest weight
.
Don't use negative weight
.
Array Solution
This algorithm will run on because of the way it uses to get the next lowest unseen node.
seen
array has size V
, and the while
loop will run for each node on the graph in worst case, making it .
A way to make it run on would be to use a minHeap
to hold the weights
.
Getting the next lowest unseen would be , and there would be no reason for the seen
array since the seen
nodes would be removed from the heap
.
The way this specific algorithm works is
Will start from the
source
node (Ex.:Node 0
), and check how much it costs to go to each of the unseen neighbors (Node 1
andNode 2
).After this check it will save:
In
weights
how much it costs to get toNode 1 = 1
andNode 2 = 5
.In
path
it will have that the best way yet to get toNode 1
andNode 2
is fromNode 0
.
Then it will check the next
unseen
node that has the lowestweight
inweights
. (So it will try to stay on the best path). In this example it will check nowNode 1
, and its unseen neighbors.After the check:
In
weights
it will have that to get toNode 2 = 7
andNode 3 = 1
. But we already know that there is a better path forNode 2
which is fromNode 0
, so reachingNode 2
fromNode 1
is ignored.In
path
we have now that reachingNode 1 & 2
should be fromNode 0
and reachingNode 3
should be fromNode 1
.
Step 2 is repeated until there are no more unseen nodes. The algorithm will prioritize paths with lowest
weight
and will override them if a better one is found.At the end it just reconstruct the
path
to return it.
Heap Solution
Last updated