graph-1
graph-1
Formally, a graph is a pair of sets (V, E), where V is the set of vertices
and E is the set of edges, connecting the pairs of vertices. Take a look at the
following graph −
V = {a, b, c, d, e}
Directed Graph
Representation of Graphs
Adjacency Matrix
Adjacency matrix is a way to represent a graph.
It shows which nodes are adjacent to one another.
Graph is represented using a square matrix.
Adjacency matrix is best for dense graph, but for sparse graph, it is not
required.
Adjacency matrix is good solution for dense graph which implies having
constant number of vertices.
Adjacency matrix of an undirected graph is always a symmetric matrix which
means an edge (i, j) implies the edge (j, i).
The above graph represents undirected graph with the adjacency matrix
representation. It shows adjacency matrix of undirected graph is symmetric. If
there is an edge (2, 4), there is also an edge (4, 2).
The above graph represents directed graph with the adjacency matrix
representation. It shows adjacency matrix of directed graph which is never
symmetric. If there is an edge (2, 4), there is not an edge (4, 2). It indicates
direct edge from vertex i to vertex j.
Advantages of Adjacency Matrix
In adjacency list, an entry array[i] represents the linked list of vertices adjacent
to the ith vertex.
Adjacency list allows to store the graph in more compact form than adjacency
matrix.
It allows to get the list of adjacent vertices in O(1) time.
Disadvantages of Adjacency List
It is not easy for adding or removing an edge to/from adjacent list.
It does not allow to make an efficient implementation, if dynamically change of
vertices number is required.
Basic Operations
Following are basic primary operations of a Graph −
Graph Traversal
Algorithm
DFS traversal of a graph produces a spanning tree as final result. Spanning Tree is a graph
without loops. We use Stack data structure with maximum size of total
number of vertices in the graph to implement DFS traversal.
Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will
pop up all the vertices from the stack, which do not have adjacent vertices.)
As C does not have any unvisited adjacent node so we keep popping the
stack until we find a node that has an unvisited adjacent node. In this case,
there's none and we keep popping until the stack is empty.
At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm
we keep on dequeuing in order to get all unvisited nodes. When the queue gets
emptied, the program is over.