Algorithms
BFS(node)
{
queue ← node
visited[node] = true
while queue not empty
v ← queue
print v
for each child c of v
if not visited[c]
queue ← c
visited[c] = true
}
DFS(node)
{
stack ← node
visited[node] = true
while stack not empty
v ← stack
print v
for each child c of v
if not visited[c]
stack ← c
visited[c] = true
}
void TraverseDFSRecursive(node)
{
if (not visited[node])
{
visited[node] = true;
print node;
foreach child node c of node
{
TraverseDFSRecursive(c);
}
}
}
void Main()
{
TraverseDFS(firstNode);
}
foreach node from graph G
{
if node is unvisited
{
DFS(node);
countOfComponents++;
}
}
Topological sorting is just sorting a directed graph that has no cycles.
So you move through the nodes of the graph till you get to the end
Then on your way back from the recursion, you push them into the stack.
Because of the way the stack orders things (reverses the order), you’ll always get the first node, then the second, and so on all the way to the last
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
insert n into L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
set all nodes DIST = INFINITY;
set current node the source and distance = 0;
Q -> all nodes from graph, ordered by distance;
while (Q is not empty)
a = dequeue the smallest element (first in PriorityQueue);
if (distance of a == INFINITY) break
foreach neighbour v of a
potDistance = distance of a + distance of (a-v)
if (potDistance < distance of v)
distance of v = potDistance;
reorder Q;