You are on page 1of 18

Graphs

By
Sonia Soans
Objectives

 At the end of this chapter students will be able to:


 Understand the concepts graphs and terminologies
 Differentiate between graphs and trees
 Apply graph traversal techniques
Graphs are one of the unifying themes of computer science.

A graph G = (V;E) is defined by a set of vertices V , and a set of edges E consisting


of ordered or unordered pairs of vertices from V.
Graph is a data structure that consists of following two components:
1.A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge.

The pair is ordered because (u, v) is not same as (v, u) in case of directed
graph(di-graph).

The pair of 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. For example, in
Facebook, each person is represented with a vertex (or node).

Graphs can be used to model social structures based on different kinds of


relationships between people or groups.
Following is an example undirected graph with 5 vertices.

Applications
Electronic applications.
Networks (roads, flights, communications)
Scheduling (project planning)
Connecting with friends on social media, where each user is a vertex,
and when users connect they create an edge.
Using GPS/Google Maps/Yahoo Maps, to find a route based on shortest
route.
Google, to search for webpages, where pages on the internet are linked
to each other by hyperlinks; each page is a vertex and the link between
two pages is an edge.
Graph theoretical concepts are widely used in Operations Research.
Graph representation

Two are the most commonly used representations of graph.


 1. Adjacency Matrix
 2. Adjacency List
Adjacency Matrix:
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 adj[][], a slot adj[i][j] = 1 indicates that there is an edge
from vertex i to vertex j. Adjacency matrix for undirected graph is always
symmetric. Adjacency Matrix is also used to represent weighted graphs. If
adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.
The adjacency matrix for the above example graph is:
Adjacency List:
An array of linked lists is used. Size of the array is equal to 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.
Following is adjacency list representation of the above graph.
Directed and Undirected Graphs
 In directed graph, edges have specific direction. In Undirected graph, edges
 are two-way.
Graph Traversals

A traversal is a systematic procedure for exploring a graph by examining all of its


vertices and edges. Some algorithms require that every vertex of a graph be visited
exactly once. The order in which the vertices are visited may be important, and may
depend upon the particular algorithm.

The two common graph traversals:

depth-first and

breadth-first.
Depth-First Search
 The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It
involves exhaustive searches of all the nodes by going ahead, if possible, else by
backtracking. Here, the word backtrack means that when you are moving
forward and there are no more nodes along the current path, you move
backwards on the same path to find nodes to traverse. All the nodes will be
visited on the current path till all the unvisited nodes have been traversed
after which the next path will be selected. This recursive nature of DFS can be
implemented using stacks. The basic idea is as follows:
 Pick a starting node and push all its adjacent nodes into a stack.
 Pop a node from stack to select the next node to visit and push all its adjacent
nodes into a stack.
 Repeat this process until the stack is empty.
 However, ensure that the nodes that are visited are marked. This will prevent
you from visiting the same node more than once. If you do not mark the nodes
that are visited and you visit the same node more than once, you may end up in
an infinite loop.
Applications of Depth First Search
For an unweighted graph, DFS traversal of the graph produces the minimum spanning tree and all
pair shortest path tree.
Detecting cycle in a graph A graph has cycle if and only if we see a back edge during DFS. So we can
run DFS for the graph and check for back edges.
Path Finding We can specialize the DFS algorithm to find a path between two given vertices u and z.
 i) Call DFS(G, u) with u as the start vertex.
 ii) Use a stack S to keep track of the path between the start vertex and the current vertex.
 iii) As soon as destination vertex z is encountered, return the path as the contents of the stack
Topological Sorting:
Tropical sorting is mainly used for scheduling jobs from the given dependencies among jobs. In
computer science, applications of this type arise in instruction scheduling, ordering of formula cell
evaluation when re computing formula values in spreadsheets, logic synthesis, determining the
order of compilation tasks to perform in make files, data serialization, and resolving symbol
dependencies in linkers.
Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all solutions to a
maze by only including nodes on the current path in the visited set.)
Depth-first-search

1. mark vertex as visited


2. for each adjacent vertex
3. if unvisited
4. do a depth-first search on adjacent vertex

dfs(G, u): while u has an unvisited neighbour in G v := an unvisited neighbour of u


mark v visited dfs(G, v)
Breadth-First Search
Breadth First Search (BFS) algorithm traverses a graph in a breadth ward motion
and uses a queue to remember to get the next vertex to start a search, when a
dead end occurs in any iteration.
The simple description of the algorithm for a BFS is this:
1. Start at some node ‘i’. This is now our current node.
2. State that our current node is ‘visited’.
3. Now look at all nodes adjacent to our current node.
4. If we see an adjacent node that has not been ‘visited’, add it to the
queue.
5. Then pull out the first node on from the queue and traverse to it.
6. And go back to step 1.
Algorithm:

BFS(G,V) Let Q be a Queue Q.enqueue(V) Label V as discovered while Q is not


empty
v <- Q.dequeue() for all edges from v to w in G.
adjacentEdges(v) do
if w is not labeled as discovered
Q.enqueue(w)
label w as discovered.
Applications
 Shortest Path, the shortest path is the path with least number of
edges. With Breadth First, we always reach a vertex from given
source using minimum number of edges. Also, in case of unweighted
graphs, any spanning tree is Minimum Spanning Tree and we can use
either Depth or Breadth first traversal for finding a spanning tree.
 Peer to Peer Networks. In Peer to Peer Networks like Bit Torrent,
Breadth First Search is used to find all neighbor nodes.
 Crawlers in Search Engines: Crawlers build index using Breadth First.
The idea is to start from source page and follow all links from source
and keep doing same. Depth First Traversal can also be used for
crawlers, but the advantage with Breadth First Traversal is, depth or
levels of built tree can be limited.
 Social Networking Websites: In social networks, we can find people
within a given distance ‘k’ from a person using Breadth First Search
till ‘k’ levels.
GPS Navigation systems: Breadth First Search is used to find all
neighboring locations.
Broadcasting in Network: In networks, a broadcasted packet follows
Breadth First Search to reach all nodes. Cycle detection in
undirected graph: In undirected graphs, either Breadth First Search
or Depth First Search can be used to detect cycle. In directed graph,
only depth first search can be used.
Ford–Fulkerson algorithm In Ford-Fulkerson algorithm, we can either
use Breadth First or Depth First Traversal to find the maximum flow.
Breadth First Traversal is preferred as it reduces worst case time
complexity to O(VE2).
Path finding, we can either use Breadth First or Depth First Traversal
to find if there is a path between two vertices.
Finding all nodes within one connected component: We can either
use Breadth First or Depth First Traversal to find all nodes reachable
Thank You

You might also like