A graph is a non-linear data structure that can be looked at as a collection of vertices potentially connected by line segments named edges.
Undirected Graph: An Undirected Graph is a graph where each edge is undirected or bi-directional.
The undirected graph we are looking at has 6 vertices and 7 undirected edges.
Undirected graph visual example:
Vertices/Nodes = {a,b,c,d,e,f}
Edges = {(a,c),(a,d),(b,c),(b,f),(c,e),(d,e),(e,f)}
Directed Graphs: A Directed Graph also called a Digraph is a graph where every edge is directed.
Direcyed graph visual example:
Vertices = {a,b,c,d,e,f}
Edges = {(a,c),(b,c),(b,f),(c,e),(d,a),(d,e)(e,c)(e,f)}
A complete graph is when all nodes are connected to all other nodes.
A connected graph is graph that has all of vertices/nodes have at least one edge.
A disconnected graph is a graph where some vertices may not have edges.
An acyclic graph is a directed graph without cycles.
A cycle is when a node can be traversed through and potentially end up back at itself.
A Cyclic graph is a graph that has cycles.
An Adjacency matrix is represented through a 2-dimensional array. If there are n vertices, then we are looking at an n x n Boolean matrix
A few things to note from the above:
An adjacency list is the most common way to represent graphs.
Code Implementation:
A weighted graph is a graph with numbers assigned to its edges. These numbers are called weights.
In a breadth first traversal, you are starting at a specific vertex/node. This node must be specified when calling the BreadthFirst() method. The breadth-first traversal of a graph is like that of a tree, with the exception that graphs can have cycles.
Algorithm:
Pseudo code:
ALGORITHM BreadthFirst(vertex)
DECLARE nodes <-- new List()
DECLARE breadth <-- new Queue()
DECLARE visited <-- new Set()
breadth.Enqueue(vertex)
visited.Add(vertex)
while (breadth is not empty)
DECLARE front <-- breadth.Dequeue()
nodes.Add(front)
for each child in front.Children
if(child is not visited)
visited.Add(child)
breadth.Enqueue(child)
return nodes;
In a depth first traversal, we approach it a bit different than the way we do when working with a depth first traversal of a tree.
Algorithm: