GRAPH
Definition
▪ A Graph in Data Structure is a non-linear data structure that consists of nodes and
edges which connects them.
▪ A Graph in Data Structure is a collection of nodes that consists of data and are
connected to other nodes of the graph.
Graph Terminologies
▪ Nodes/Vertices:
▪ Vertices are the fundamental units of the graph.
▪ Every node/vertex can be labeled or unlabelled.
▪ A node can represent anything such as any location, port, houses, buildings, landmarks, etc.
▪ Edges/Arcs:
▪ Edges are drawn or used to connect two nodes of the graph.
▪ It can be ordered pair of nodes in a directed graph.
▪ Edges can connect any two nodes in any possible way. There are no rules.
▪ Every edge can be labeled/unlabelled.
▪ A graph data structure (V,E) consists of:
▪ A collection of vertices (V) or nodes.
▪ A collection of edges (E) or path
OR
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. In this graph:
▪ V = {a, b, c, d}
▪ E = {ab, ac, ad, bc, cd}
▪ In this graph, |V| = 4 because there are four nodes (vertices) and, |E| = 5 because
there are five edges (lines).
▪ Path: A sequence of vertices in which each vertex is adjacent to the next one
In the above graph, the path from 'a' to 'e' is = {a,b,c,d,e}
▪ Adjacent vertices: Two vertices in a graph are said to be adjacent vertices (or
neighbors) if there is a path of length 1 connecting them.
Degree of a Node
▪ Cycle: a path that starts and ends on the same vertex
▪ Simple path: a path that does not cross itself
▪ That is, no vertex is repeated (except first and last)
▪ Simple paths cannot contain cycles
A sequence of vertices: (A, B, C, D) [Is this path, simple
path, cycle?]
(A, B, D, A, C) [path, simple path, cycle?]
(A, B, D, A, C) [path, simple path, cycle?]
Cycle: ?
▪ Complete Graph: A graph in which every vertex is connected to every other vertex
▪ Simple Graph: A graph which does not contain any loop or multiple edges
▪ Multiple edges: Two nodes can be connected using more than 1 edges
▪ Loop : an edge connects a vertex to itself
Types of Graph
▪ Directed Graphs: Directed graphs in graph data structure are the graphs where the
edges have directions from one node towards the other node.
▪ Undirected Graphs: Undirected graphs have edges that do not have a direction.
Hence, the graph can be traversed in either direction.
▪ Weighted Graph: In weighted graphs, each edge has a value associated with them
(called weight). It refers to a simple graph that has weighted edges. The weights are
usually used to compute the shortest path in the graph.
Directed Graph Undirected Graph Weighted Graph
▪ Finite Graph: The graph G=(V, E) is called a finite graph if the number of vertices and
edges in the graph is limited in number
▪ Infinite Graph: The graph G=(V, E) is called a finite graph if the number of vertices
and edges in the graph is interminable.
▪ Trivial Graph: A graph G= (V, E) is trivial if it contains only a single vertex and no
edges.
▪ Multi Graph: If there are numerous edges between a pair of vertices in a graph G= (V,
E), the graph is referred to as a multigraph.
▪ Null Graph: It's a reworked version of a trivial graph. If several vertices but no edges
connect them, a graph G= (V, E) is a null graph.
▪ Complete Graph: Every vertex is directly connected to every other vertex
▪ Connected Graph: If there is a path between one vertex of a graph data structure to
any other vertex, the graph is connected.
▪ Cyclic Graph: If a graph contains at least one graph cycle, it is considered to be
cyclic.
▪ Acyclic Graph : When there are no cycles in a graph, it is called an acyclic graph.
▪ Directed Acyclic Graph: It's also known as a directed acyclic graph (DAG), and it's a
graph with directed edges but no cycle. It represents the edges using an ordered pair
of vertices since it directs the vertices and stores some data.
▪ Subgraph: The vertices and edges of a graph that are subsets of another graph are
known as a subgraph.
▪ Disjoint Graph: A graph is disjoint if it is not connected
Graph Representation
▪ In graph data structure, a graph representation is a technique to store graph into the
memory of computer.
▪ There are 2 ways
▪ Adjacency Matrix
▪ Adjacency List
Adjacency Matrix
▪ An Adjacency Matrix is a 2D array of size V x V where V is the number of nodes in a
graph.
▪ It is used to represent a "finite graph", with 0's and 1's.
▪ The elements of the matrix indicates whether pairs of vertices are adjacent or not in
the graph
▪ Each cell in the above matrix is represented as Aij, where i and j are nodes. The value
of Aij is either 1 or 0 depending on whether there is an edge from vertex i to vertex j. If
there is a node then, Aij= 1, otherwise Aij= 0
▪ The adjacency Matrix for a directed graph also follows the same conventions
▪ there is a '1' in the matrix if there is an edge pointing from one node to another, say
from node A to node B. But vice versa may not be applicable.
Advantages of using Adjacency Matrix
Disadvantages of using Adjacency Matrix
Adjacency List
▪ An adjacency list represents a graph as an array of linked lists.
▪ The index of the array represents a node.
▪ Each element in the linked list represents the nodes that are connected to that node
by an edge.
Advantages of using Adjacency List
Tree as a Graph
What is Graph Traversal
▪ Traversing a graph means visiting each vertex in a graph.
▪ Since a graph can contain cycles it might be possible that single vertex can be visited
twice and can reduce the efficiency.
▪ So it is very important to traverse the graph in such a way that each vertex must be
visited only once.
▪ Two techniques are proposed for such kind of graph traversal.
▪ DFS (Depth First Search)
▪ BFS (Breadth First Search)
DFS (Depth First Search)
▪ Recursive algorithm to search (Traverse) all the vertices of a tree data structure or a
graph.
▪ Because of the recursive nature, stack data structure can be used to implement the
DFS algorithm
▪ A standard DFS implementation puts each vertex of the graph into one of two
categories:
▪ Visited
▪ Not Visited
▪ The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
DFS Traversal
▪ Step 1: SET STATUS = 1 (ready state) for each node in G
▪ Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
▪ Step 3: Repeat Steps 4 and 5 until STACK is empty
▪ Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
▪ Step 5: Push on the stack all the neighbors of N that are in the ready state (whose STATUS = 1) and
set their STATUS = 2 (waiting state)
▪ [END OF LOOP]
▪ Step 6: EXIT
Pseudocode
DFS(G,v) ( v is the vertex where the search starts )
Stack S := {}; ( start with an empty stack )
for each vertex u, set visited[u] := false;
push S, v;
while (S is not empty) do
u := pop S;
if (not visited[u]) then
visited[u] := true;
for each unvisited neighbor w of u
push S, w;
end if
end while
END DFS()
Example
1 2 3
4 5 6
BFS (Breadth First Search)
▪ It is a recursive algorithm to search all the vertices of a tree or graph data structure
▪ puts every vertex of the graph into two categories - visited and non-visited.
▪ It selects a single node in a graph and, after that, visits all the nodes adjacent to the
selected node.
BFS Traversal
▪ Step 1: SET STATUS = not visited (ready state) for each node in G
▪ Step 2: Enqueue the starting node A and set its STATUS = Waiting
▪ Step 3: Repeat Steps 4 and 5 until QUEUE is empty
▪ Step 4: Dequeue a node N. Process it and set its STATUS =3 (Visited/Processed)
▪ Step 5: Enqueue all the neighbors of N that are in the ready state (whose STATUS = 1) and set their
STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
Pseudocode
BFS(G,v) ( v is the vertex where the search starts )
Queue Q := {}; ( start with an empty queue )
for each vertex u, set visited[u] := false;
enque Q, v;
while (Q is not empty) do
u := Deque Q;
if (not visited[u]) then
visited[u] := true;
for each unvisited neighbour w of u
enque Q, w;
end if
end while
END BFS()
BFS Example
1 2 3
4 5 6
7
Applications of Graph
▪ Graphs are used in computer science to depict the flow of computation.
▪ Users on Facebook are referred to as vertices, and if they are friends, there is an edge
connecting them. The Friend Suggestion system on Facebook is based on graph theory.
▪ You come across the Resource Allocation Graph in the Operating System, where each process
and resource are regarded vertically. Edges are drawn from resources to assigned functions or
from the requesting process to the desired resource. A stalemate will develop if this results in the
establishment of a cycle.
▪ Web pages are referred to as vertices on the World Wide Web. Suppose there is a link from page
A to page B that can represent an edge. This application is an illustration of a directed graph.
▪ Graph transformation systems manipulate graphs in memory using rules. Graph databases store
and query graph-structured data in a transaction-safe, permanent manner.
▪ GPS systems and Google Maps use graphs to find the shortest path from one destination to
another.
Shortest Path Algorithm
▪ The shortest path problem is about finding a path between vertices in a graph such
that the total sum of the edges weights is minimum.
▪ Dijkstra's Algorithm: Dijkstra's Algorithm works on the basis that any subpath B -> D
of the shortest path A -> D between vertices A and D is also the shortest path between
vertices B and D.
Dijkstra's Algorithm
▪ Initialization:
▪ D(s) : Shortest distance to s is set to 0
▪ For all other vertices v D(v) is set to ∞
▪ Priority Queue PQ is constructed which is initially holds all the vertices of graph. Each vertex v have the
priority D(v)
1. Pick up the first minimum element from the priority queue PQ
2. For all the vertices adjacent to s
1. Check if the edge from s->v gives shortest path
if (D(s) + weight of edge s->v) < D(v)
D(v)= D(s) + weight of edge s->v
3. Pick the next element from Priority queue PQ and repeat the process until PQ is empty
Minimum Spanning Tree
▪ What is a Spanning Tree?
A spanning tree is a sub-graph of an undirected connected graph, which includes all the
vertices of the graph with a minimum possible number of edges. If a vertex is missed,
then it is not a spanning tree.
▪ Minimum Spanning Tree
A minimum spanning tree is a spanning tree in which the sum of the weight of the edges
is as minimum as possible.
Kruskal’s Algorithm
▪ Sort all the edges in ascending order of their weight
▪ Pick the edge with the lowest weight and add it to the spanning tree. If adding the
edge created a cycle, then reject this edge.
▪ Repeat step 2 until there are (v-1) edges in the spanning tree
Prim’s Algorithm
▪ Initialize visited array to 0
▪ Count=0
▪ While count < vertices
▪ If newVertex is not visited
▪ Mark newVertex as visited
▪ Push all its edges to priority Queue
▪ Extract the minimum edge from priority queue
▪ If the minimum edge leads to an unvisited vertex add it to Minimum spanning tree
▪ Current=newVertex
▪ Count++
▪ Else
▪ Extract the minimum edge from priority again
▪ If the minimum edge leads to an unvisited vertex add it to Minimum spanning tree
▪ Current=newVertex
Data Structure and algorithms - Graph1.pptx
Data Structure and algorithms - Graph1.pptx
Data Structure and algorithms - Graph1.pptx
Data Structure and algorithms - Graph1.pptx

Data Structure and algorithms - Graph1.pptx

  • 1.
  • 2.
    Definition ▪ A Graphin Data Structure is a non-linear data structure that consists of nodes and edges which connects them. ▪ A Graph in Data Structure is a collection of nodes that consists of data and are connected to other nodes of the graph.
  • 3.
    Graph Terminologies ▪ Nodes/Vertices: ▪Vertices are the fundamental units of the graph. ▪ Every node/vertex can be labeled or unlabelled. ▪ A node can represent anything such as any location, port, houses, buildings, landmarks, etc.
  • 4.
    ▪ Edges/Arcs: ▪ Edgesare drawn or used to connect two nodes of the graph. ▪ It can be ordered pair of nodes in a directed graph. ▪ Edges can connect any two nodes in any possible way. There are no rules. ▪ Every edge can be labeled/unlabelled.
  • 5.
    ▪ A graphdata structure (V,E) consists of: ▪ A collection of vertices (V) or nodes. ▪ A collection of edges (E) or path OR 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. In this graph: ▪ V = {a, b, c, d} ▪ E = {ab, ac, ad, bc, cd} ▪ In this graph, |V| = 4 because there are four nodes (vertices) and, |E| = 5 because there are five edges (lines).
  • 7.
    ▪ Path: Asequence of vertices in which each vertex is adjacent to the next one In the above graph, the path from 'a' to 'e' is = {a,b,c,d,e} ▪ Adjacent vertices: Two vertices in a graph are said to be adjacent vertices (or neighbors) if there is a path of length 1 connecting them.
  • 8.
    Degree of aNode ▪ Cycle: a path that starts and ends on the same vertex ▪ Simple path: a path that does not cross itself ▪ That is, no vertex is repeated (except first and last) ▪ Simple paths cannot contain cycles A sequence of vertices: (A, B, C, D) [Is this path, simple path, cycle?] (A, B, D, A, C) [path, simple path, cycle?] (A, B, D, A, C) [path, simple path, cycle?] Cycle: ?
  • 9.
    ▪ Complete Graph:A graph in which every vertex is connected to every other vertex ▪ Simple Graph: A graph which does not contain any loop or multiple edges ▪ Multiple edges: Two nodes can be connected using more than 1 edges ▪ Loop : an edge connects a vertex to itself
  • 12.
    Types of Graph ▪Directed Graphs: Directed graphs in graph data structure are the graphs where the edges have directions from one node towards the other node. ▪ Undirected Graphs: Undirected graphs have edges that do not have a direction. Hence, the graph can be traversed in either direction. ▪ Weighted Graph: In weighted graphs, each edge has a value associated with them (called weight). It refers to a simple graph that has weighted edges. The weights are usually used to compute the shortest path in the graph. Directed Graph Undirected Graph Weighted Graph
  • 13.
    ▪ Finite Graph:The graph G=(V, E) is called a finite graph if the number of vertices and edges in the graph is limited in number ▪ Infinite Graph: The graph G=(V, E) is called a finite graph if the number of vertices and edges in the graph is interminable.
  • 14.
    ▪ Trivial Graph:A graph G= (V, E) is trivial if it contains only a single vertex and no edges. ▪ Multi Graph: If there are numerous edges between a pair of vertices in a graph G= (V, E), the graph is referred to as a multigraph. ▪ Null Graph: It's a reworked version of a trivial graph. If several vertices but no edges connect them, a graph G= (V, E) is a null graph.
  • 15.
    ▪ Complete Graph:Every vertex is directly connected to every other vertex ▪ Connected Graph: If there is a path between one vertex of a graph data structure to any other vertex, the graph is connected.
  • 16.
    ▪ Cyclic Graph:If a graph contains at least one graph cycle, it is considered to be cyclic. ▪ Acyclic Graph : When there are no cycles in a graph, it is called an acyclic graph.
  • 17.
    ▪ Directed AcyclicGraph: It's also known as a directed acyclic graph (DAG), and it's a graph with directed edges but no cycle. It represents the edges using an ordered pair of vertices since it directs the vertices and stores some data.
  • 18.
    ▪ Subgraph: Thevertices and edges of a graph that are subsets of another graph are known as a subgraph.
  • 19.
    ▪ Disjoint Graph:A graph is disjoint if it is not connected
  • 20.
    Graph Representation ▪ Ingraph data structure, a graph representation is a technique to store graph into the memory of computer. ▪ There are 2 ways ▪ Adjacency Matrix ▪ Adjacency List
  • 21.
    Adjacency Matrix ▪ AnAdjacency Matrix is a 2D array of size V x V where V is the number of nodes in a graph. ▪ It is used to represent a "finite graph", with 0's and 1's. ▪ The elements of the matrix indicates whether pairs of vertices are adjacent or not in the graph ▪ Each cell in the above matrix is represented as Aij, where i and j are nodes. The value of Aij is either 1 or 0 depending on whether there is an edge from vertex i to vertex j. If there is a node then, Aij= 1, otherwise Aij= 0
  • 22.
    ▪ The adjacencyMatrix for a directed graph also follows the same conventions ▪ there is a '1' in the matrix if there is an edge pointing from one node to another, say from node A to node B. But vice versa may not be applicable.
  • 23.
    Advantages of usingAdjacency Matrix
  • 24.
    Disadvantages of usingAdjacency Matrix
  • 25.
    Adjacency List ▪ Anadjacency list represents a graph as an array of linked lists. ▪ The index of the array represents a node. ▪ Each element in the linked list represents the nodes that are connected to that node by an edge.
  • 26.
    Advantages of usingAdjacency List
  • 27.
    Tree as aGraph
  • 28.
    What is GraphTraversal ▪ Traversing a graph means visiting each vertex in a graph. ▪ Since a graph can contain cycles it might be possible that single vertex can be visited twice and can reduce the efficiency. ▪ So it is very important to traverse the graph in such a way that each vertex must be visited only once. ▪ Two techniques are proposed for such kind of graph traversal. ▪ DFS (Depth First Search) ▪ BFS (Breadth First Search)
  • 29.
    DFS (Depth FirstSearch) ▪ Recursive algorithm to search (Traverse) all the vertices of a tree data structure or a graph. ▪ Because of the recursive nature, stack data structure can be used to implement the DFS algorithm ▪ A standard DFS implementation puts each vertex of the graph into one of two categories: ▪ Visited ▪ Not Visited ▪ The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
  • 30.
    DFS Traversal ▪ Step1: SET STATUS = 1 (ready state) for each node in G ▪ Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state) ▪ Step 3: Repeat Steps 4 and 5 until STACK is empty ▪ Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state) ▪ Step 5: Push on the stack all the neighbors of N that are in the ready state (whose STATUS = 1) and set their STATUS = 2 (waiting state) ▪ [END OF LOOP] ▪ Step 6: EXIT
  • 31.
    Pseudocode DFS(G,v) ( vis the vertex where the search starts ) Stack S := {}; ( start with an empty stack ) for each vertex u, set visited[u] := false; push S, v; while (S is not empty) do u := pop S; if (not visited[u]) then visited[u] := true; for each unvisited neighbor w of u push S, w; end if end while END DFS()
  • 32.
  • 34.
    BFS (Breadth FirstSearch) ▪ It is a recursive algorithm to search all the vertices of a tree or graph data structure ▪ puts every vertex of the graph into two categories - visited and non-visited. ▪ It selects a single node in a graph and, after that, visits all the nodes adjacent to the selected node.
  • 35.
    BFS Traversal ▪ Step1: SET STATUS = not visited (ready state) for each node in G ▪ Step 2: Enqueue the starting node A and set its STATUS = Waiting ▪ Step 3: Repeat Steps 4 and 5 until QUEUE is empty ▪ Step 4: Dequeue a node N. Process it and set its STATUS =3 (Visited/Processed) ▪ Step 5: Enqueue all the neighbors of N that are in the ready state (whose STATUS = 1) and set their STATUS = 2 (waiting state) [END OF LOOP] Step 6: EXIT
  • 36.
    Pseudocode BFS(G,v) ( vis the vertex where the search starts ) Queue Q := {}; ( start with an empty queue ) for each vertex u, set visited[u] := false; enque Q, v; while (Q is not empty) do u := Deque Q; if (not visited[u]) then visited[u] := true; for each unvisited neighbour w of u enque Q, w; end if end while END BFS()
  • 37.
    BFS Example 1 23 4 5 6 7
  • 39.
    Applications of Graph ▪Graphs are used in computer science to depict the flow of computation. ▪ Users on Facebook are referred to as vertices, and if they are friends, there is an edge connecting them. The Friend Suggestion system on Facebook is based on graph theory. ▪ You come across the Resource Allocation Graph in the Operating System, where each process and resource are regarded vertically. Edges are drawn from resources to assigned functions or from the requesting process to the desired resource. A stalemate will develop if this results in the establishment of a cycle. ▪ Web pages are referred to as vertices on the World Wide Web. Suppose there is a link from page A to page B that can represent an edge. This application is an illustration of a directed graph. ▪ Graph transformation systems manipulate graphs in memory using rules. Graph databases store and query graph-structured data in a transaction-safe, permanent manner. ▪ GPS systems and Google Maps use graphs to find the shortest path from one destination to another.
  • 42.
    Shortest Path Algorithm ▪The shortest path problem is about finding a path between vertices in a graph such that the total sum of the edges weights is minimum. ▪ Dijkstra's Algorithm: Dijkstra's Algorithm works on the basis that any subpath B -> D of the shortest path A -> D between vertices A and D is also the shortest path between vertices B and D.
  • 43.
    Dijkstra's Algorithm ▪ Initialization: ▪D(s) : Shortest distance to s is set to 0 ▪ For all other vertices v D(v) is set to ∞ ▪ Priority Queue PQ is constructed which is initially holds all the vertices of graph. Each vertex v have the priority D(v) 1. Pick up the first minimum element from the priority queue PQ 2. For all the vertices adjacent to s 1. Check if the edge from s->v gives shortest path if (D(s) + weight of edge s->v) < D(v) D(v)= D(s) + weight of edge s->v 3. Pick the next element from Priority queue PQ and repeat the process until PQ is empty
  • 48.
    Minimum Spanning Tree ▪What is a Spanning Tree? A spanning tree is a sub-graph of an undirected connected graph, which includes all the vertices of the graph with a minimum possible number of edges. If a vertex is missed, then it is not a spanning tree.
  • 49.
    ▪ Minimum SpanningTree A minimum spanning tree is a spanning tree in which the sum of the weight of the edges is as minimum as possible.
  • 50.
    Kruskal’s Algorithm ▪ Sortall the edges in ascending order of their weight ▪ Pick the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle, then reject this edge. ▪ Repeat step 2 until there are (v-1) edges in the spanning tree
  • 55.
    Prim’s Algorithm ▪ Initializevisited array to 0 ▪ Count=0 ▪ While count < vertices ▪ If newVertex is not visited ▪ Mark newVertex as visited ▪ Push all its edges to priority Queue ▪ Extract the minimum edge from priority queue ▪ If the minimum edge leads to an unvisited vertex add it to Minimum spanning tree ▪ Current=newVertex ▪ Count++ ▪ Else ▪ Extract the minimum edge from priority again ▪ If the minimum edge leads to an unvisited vertex add it to Minimum spanning tree ▪ Current=newVertex

Editor's Notes

  • #1 NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image.