## Monday, 11 September 2017

### Algorithms | Graph and its representations

What is Graph?
A set of items connected by edges, each item is called a vertex or node. Formally, a graph is a set of vertices and a binary relation between vertices, adjacency.

A graph is a data structure that consists of two components:
1. A finite set of vertices also called as nodes.
2. A finite set of the ordered pair of the form (u, v) called as an edge. The pair is ordered because (u, v) is not same as (v, u) in case of a directed graph (di-graph). The pair of the form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.

Graphs are used to represent many real life applications: Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook.

Facebook: Each user is represented as a vertex and two people are friends when there is an edge between two vertices. Similarly, friend suggestion also uses graph theory concept.

Google Maps: Various locations are represented as vertices and the roads are represented as edges and graph theory is used to find the shortest path between two nodes.

Recommendations on e-commerce websites: The “Recommendations for you” section on various e-commerce websites uses graph theory to recommend items of similar type to user’s choice.

Chemistry:
Graph theory is also used to study molecules in chemistry and physics.

Graph representation?
Most commonly used representations of the graph:

Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph.
Let the 2D array be graph[][], a slot graph[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. For weighted graphs, if graph [i][j] = w, then there is an edge from vertex i to vertex j with weight w in Adjacency Matrix.

package com.graph;
import java.util.Scanner;

/**
* This class is written for Graph Adjacency Matrix.
* @author algos.debug
*/
private final int MAX_VERTICES;
private int graph[][];

MAX_VERTICES = nVertices;
graph = new int[MAX_VERTICES + 1][MAX_VERTICES + 1];
}

/**
* This method is used to set the edge of the graph.
* @param fromVertex
* @param toVertex
* @param edge
*/
public void setEdge(int fromVertex, int toVertex, int edge) {
try {
graph[fromVertex][toVertex] = edge;
} catch (ArrayIndexOutOfBoundsException indexBounce) {
System.out.println("Entered vertex is not present");
}
}

/**
* @param fromVertex
* @param toVertex
* @return the edge between two vertices.
*/
public int getEdge(int fromVertex, int toVertex) {
try {
return graph[fromVertex][toVertex];
} catch (ArrayIndexOutOfBoundsException indexBounce) {
System.out.println("Entered vertex is not present");
}
return -1;
}

/**
* Driver method.
* @param arg
*/
public static void main(String... arg) {
int vertices, count = 1;
int source = 0, destination = 0;
int WEIGHT = 1;

try(Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the Number of Vertices");
vertices = scan.nextInt();
System.out.println("Enter the Number of Edges");
int edges = scan.nextInt();

System.out.println("Enter The Graph Egdes :<source> <destination>");
while (count <= edges) {
source = scan.nextInt();
destination = scan.nextInt();
count++;
}

System.out.println("The adjacency matrix for given graph is");
for (int i = 1; i <= vertices; i++) {
System.out.print(i);
}

System.out.println();
for (int i = 1; i <= vertices; i++) {
System.out.print(i);
for (int j = 1; j <= vertices; j++) {
}
System.out.println();
}

scan.close();
}
}
}

Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).

Cons: It consumes more space O(V^2). Even if the graph is sparse (contains less number of edges), it consumes the same space. Adding a new vertex is O(V^2) time.

An array of linked lists is used and the size of the array is equal to the number of vertices.
Let the array be array[]. An entry array[i] represents the linked list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be stored in nodes of linked lists.

package com.graph;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

for (int i = 1; i <= verticesi++) {
}
}

public void setEdge(int source, int destination) {
System.out.println("Entered vertex is not present ");
return;
}
}

public List<Integer> getEdge(int source) {
System.out.println("the vertex entered is not present");
return null;
}
}

public static void main(String...arg) {
int source, destination;
int number_of_edges, vertices;
int count = 1;
Scanner scan = new Scanner(System.in);
try {
System.out.println("Enter the number of vertices and edges in graph");
vertices = scan.nextInt();
number_of_edges = scan.nextInt();

System.out.println("Enter the edges in graph Format : <source index> <destination index>");
while (count <= number_of_edges) {
source = scan.nextInt();
destination = scan.nextInt();
count++;
}
System.out.println("the given Adjacency List for the graph \n");
for (int i = 1; i <= vertices; i++) {
System.out.print(i+"->");
for (int j = 1; ; j++ ) {
if (j != edgeList.size()) {
System.out.print(edgeList.get(j - 1 ) + "->");
} else {
System.out.print(edgeList.get(j - 1 ));
break;
}
}
System.out.println();
}
}catch (InputMismatchException inputMismatch) {
System.out.println("Error in Input Format. \nFormat : <source index> <destination index>");
}
scan.close();
}
}

Pros: Saves space O(|V|+|E|). In the worst case, there can be C(V, 2) number of edges in a graph thus consuming O(V^2) space. Adding a vertex is easier.

Cons: Queries like whether there is an edge from vertex u to vertex v are not efficient and can be done O(V).

Representations of an undirected graph:
Representations of an directed graph: