Graph Mapping
Graph Mapping
Introduction
A graph is an abstract data structure that is used to implement the mathematical concept of graphs. It is
basically a collection of vertices (also called nodes) and edges that connect these vertices. A graph is
often viewed as a generalization of the tree structure, where instead of having a purely parent-to-child
relationship between tree nodes, any kind of complex relationship can exist.
Definition
A graph G is defined as an ordered set (V, E), where V(G) represents the set of vertices and E(G)
represents the edges that connect these vertices. Figure 13.1 shows a graph with V(G) = {A, B, C, D and
E} and E(G) = {(A, B), (B, C), (A, D), (B, D), (D, E), (C, E)}. Note that there are five vertices or nodes and six
edges in the graph.
Types of graph
a) Directed Graphs
A directed graph G, also known as a digraph, is a graph in which every edge has a direction
assigned to it. An edge of a directed graph is given as an ordered pair (u, v) of nodes in G. For an
edge (u, v),
The edge begins at u and terminates at v.
u is known as the origin or initial point of e. Correspondingly, v is known as the
destination or terminal point of e.
u is the predecessor of v. Correspondingly, v is the successor of u.
Nodes u and v are adjacent to each other
b) Undirected Graph
In an undirected graph, edges do not have any direction associated with them. That is, if an edge
is drawn between nodes A and B, then the nodes can be traversed from A to B as well as from B
to A. Figure shows an undirected graph because it does not give any information about the
direction of the edges
c) Weighted graph
A graph where each edge has assigned a particular value called weight or cost.
Representation of Graphs:
There are two common ways of storing graphs in the computer’s memory. They are:
An adjacency matrix is used to represent which nodes are adjacent to one another. By definition,
two nodes are said to be adjacent if there is an edge connecting them. In a directed graph G, if node
v is adjacent to node u, then there is definitely an edge from u to v. That is, if v is adjacent to u, we
can get from u to v by traversing one edge. For any graph G having n nodes, the adjacency matrix
will have the dimension of n ¥ n. In an adjacency matrix, the rows and columns are labelled by graph
vertices.
Adjacency list representation:
An adjacency list is another way in which graphs can be represented in the computer’s memory. This
structure consists of a list of all nodes in G. Furthermore, every node is in turn linked to its own list that
contains the names of all other nodes that are adjacent to it.
C++ Code for list and matrix:
#include <iostream>
#include <vector>
adj[u].push_back(v);
adj[v].push_back(u);
matrix[i][v] = 1;
matrix[v][i] = 1;
return matrix;
int main() {
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
return 0;