A graph is a non-linear data structure that can be looked at as a collection of vertices (or nodes) potentially connected by line segments named edges.
Terminology:
Complete Graphs: A complete graph is when all nodes are connected to all other nodes.
Disconnected Graphs: It is a graph in which some node may not have edges.
Connected Graphs : A connected graph is graph that has all of vertices/nodes have at least one edge.
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.
We can use either use Breadth First or Depth First in travelling in the graph.
Breadth First
Breadth first traversal is when you visit all the nodes that are closest to the root as possible
Algorithm:
Enqueue
the declared start node into the Queue.Dequeue
the first node from the queuevisited
set and insert them into the queue.Depth First
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. Similar to how the breadth-first uses a queue, we are going to use a Stack for our depth-first traversal.
Algorithm:
Push
the root node into the stackPeek
at the top node in the stackPush
any unvisited children back into the stack.Pop
that node off the stack