You are on page 1of 7

Graph

What is a Graph?
A graph is a Non-Linear Data Structure which consists of set of nodes called vertices V and
set of edges E which links vertices. The set of edges describes relationships among the
vertices.
Formal definition of Graph
A graph G is defined as follows:
G=(V,E)
V(G): a finite, nonempty set of vertices
E(G): a set of edges (pairs of vertices)
Directed vs. undirected Graph
When the edges in a graph have no direction, the graph is called undirected
UNDIRECTED GRAPH

When the edges in a graph have a direction, the graph is called directed (or digraph). If
the graph is directed, the order of the vertices in each edge is important.
DIRECTED GRAPH

Graph vs. Tree


Trees are special cases of graphs.

GRAPH TERMINOLOGY
Adjacent nodes: Two nodes are adjacent if they are connected by an edge.
5 is adjacent to 7

7 is adjacent from 5

Path: A sequence of vertices that connect two nodes in a graph


Complete graph: A graph in which every vertex is directly connected to every other
vertex.
What is the number of edges in a complete directed graph with N vertices?
N * (N-1)

What is the number of edges in a complete undirected graph with N vertices?


N * (N-1) / 2

Weighted graph: A graph in which each edge carries a value.

Sequential Representation of Graphs


ADJACENCY MATRIX
The most frequently used graph representation scheme is the adjacency matrix also referred
as incidence matrix. A graph containing n vertices can be represented by a matrix with n
rows and n columns. The matrix is formed by storing 1 in its ithrow and jth column of the
matrix, if there exists an edge between ith and jth vertex of the graph, and a 0, if there is no
edge between ith and jth vertex of the graph.

LINKED LIST REPRESENTATION OF GRAPHS


3

A schematic diagram of a linked representation of G in memory. Specifically, the linked


representation will contain two lists (or files), a node list NODE and an edge list EDGE, as
follows.

GRAPH IMPLEMENTATION
Array-based implementation
A 1D array is used to represent the vertices.
A 2D array (adjacency matrix) is used to represent the edges.
Linked-list implementation
A 1D array is used to represent the vertices.
A list is used for each vertex v which contains the vertices which are adjacent
from v (adjacency list).
GRAPH SEARCHING
Methods: Depth-First-Search (DFS) or Breadth-First-Search (BFS).
Depth-First-Search (DFS)
What is the idea behind DFS?
Travel as far as you can down a path
4

Back up as little as possible when you reach a "dead end" (i.e., next vertex
has been "marked" or there is no next vertex).
DFS can be implemented efficiently using a stack.
Breadth-First-Searching (BFS)
What is the idea behind BFS?
Look at all possible paths at the same depth before you go at a deeper level.
Back up as far as possible when you reach a "dead end" (i.e., next vertex has
been "marked" or there is no next vertex).
BFS can be implemented efficiently using a queue.

Graph Program Implementation Java


import java.io.*;
import java.util.*;
public class algo {
private static final Graph.Edge[]
GRAPH = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
new Graph.Edge("c", "d", 11),
new Graph.Edge("c", "f", 2),
new Graph.Edge("d", "e", 6),
new Graph.Edge("e", "f", 9),
};
private static final String START
= "a";
private static final String END =
"e";
public static void main(String[]
args) {
Graph g = new
Graph(GRAPH);
g.algo(START);
g.printPath(END);
//g.printAllPaths();
}
}
class Graph {
private final Map<String, Vertex>
graph; // mapping of vertex names
to Vertex objects, built from a set of
Edges
/** One edge of the graph (only
used by Graph constructor) */
public static class Edge {
public final String v1, v2;
public final int dist;
public Edge(String v1, String
v2, int dist) {
this.v1 = v1;
this.v2 = v2;
this.dist = dist;
}
}
/** One vertex of the graph,
complete with mappings to
neighbouring vertices */
public static class Vertex
implements Comparable<Vertex> {
public final String name;
public int dist =
Integer.MAX_VALUE; //
MAX_VALUE assumed to be
infinity
public Vertex previous = null;
public final Map<Vertex, Integer>

} else if (this.previous == null) {


System.out.printf("%s(unreached)",
this.name);
} else {
this.previous.printPath();
System.out.printf(" -> %s(%d)",
this.name, this.dist);
}
}
public int compareTo(Vertex other) {
return Integer.compare(dist, other.dist);
}
}
/** Builds a graph from a set of edges */
public Graph(Edge[] edges) {
graph = new HashMap<>(edges.length);
//one pass to find all vertices
for (Edge e : edges) {
if (!graph.containsKey(e.v1))
graph.put(e.v1, new Vertex(e.v1));
if (!graph.containsKey(e.v2))
graph.put(e.v2, new Vertex(e.v2));
}
//another pass to set neighbouring vertices
for (Edge e : edges) {
graph.get(e.v1).neighbours.put(graph.get(e.v2),
e.dist);
//graph.get(e.v2).neighbours.put(graph.get(e.v1),
e.dist); // also do this for an undirected graph
}
}
/** Runs algo using a specified source vertex */
public void algo(String startName) {
if (!graph.containsKey(startName)) {
System.err.printf("Graph doesn't contain
start vertex \"%s\"\n", startName);
return;
}
final Vertex source = graph.get(startName);
NavigableSet<Vertex> q = new TreeSet<>();
// set-up vertices
for (Vertex v : graph.values()) {
v.previous = v == source ? source : null;
v.dist = v == source ? 0 :
Integer.MAX_VALUE;
q.add(v);
}
algo(q);
}

}
private void printPath() {
if (this == this.previous) {
System.out.printf("%s",
this.name);
private void algo(final
NavigableSet<Vertex> q) {
Vertex u, v;
while (!q.isEmpty()) {
u = q.pollFirst(); // vertex with
shortest distance (first iteration will
return source)
if (u.dist ==
Integer.MAX_VALUE) break; // we
can ignore u (and any other remaining
vertices) since they are unreachable
//look at distances to each
neighbour
for (Map.Entry<Vertex, Integer>
a : u.neighbours.entrySet()) {
v = a.getKey(); //the neighbour
in this iteration
final int alternateDist = u.dist +
a.getValue();
if (alternateDist < v.dist) { //
shorter path to neighbour found
q.remove(v);
v.dist = alternateDist;
v.previous = u;
q.add(v);
}
}
}
}
/** Prints a path from the source to
the specified vertex */
public void printPath(String
endName) {
if (!graph.containsKey(endName))
{
System.err.printf("Graph doesn't
contain end vertex \"%s\"\n",
endName);
return;
}
graph.get(endName).printPath();
System.out.println();
}
/** Prints the path from the source to
every vertex (output order is not
guaranteed) */
public void printAllPaths() {
for (Vertex v : graph.values()) {

neighbours = new HashMap<>();


public Vertex(String name) {
this.name = name;

/** Implementation of algo's using a binary


heap. */

v.printPath();
System.out.println();
} }}

Output:

You might also like