SlideShare a Scribd company logo
1 of 7
Download to read offline
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU.
▪ Graph:
A graph 𝐺 = (𝑉, 𝐸) consists of two sets,
𝑉 = set of vertices (nodes)
𝐸 = set of edges = subset of (𝑉 × 𝑉)
▪ Representation
1. Adjacency Matrix:
• Undirected graph
1
2
3
4
5
6 [
0 1 0 0 1 0
1 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0
1 1 0 0 0 0
0 0 1 0 0 0]
• Weighted undirected graph
1
2
3
4
5
6 [
∞ 5 ∞ ∞ 11 ∞
5 ∞ ∞ ∞ 6 ∞
∞ ∞ ∞ ∞ ∞ 10.5
∞ ∞ ∞ ∞ ∞ ∞
11 6 ∞ ∞ ∞ ∞
∞ ∞ 10.5 ∞ ∞ ∞ ]
• Directed graph
1
2
3
4
5
6 [
0 1 0 0 0 0
0 0 0 1 1 0
0 0 0 0 0 0
1 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0]
• Weighted directed graph
1
2
3
4
5
6 [
∞ 7.8 ∞ ∞ ∞ ∞
∞ ∞ ∞ 11 8.1 ∞
∞ ∞ ∞ ∞ ∞ ∞
7.6 ∞ ∞ ∞ 9 ∞
∞ ∞ ∞ 8.8 ∞ ∞
∞ ∞ 12 ∞ ∞ ∞]
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU.
2. Adjacency List:
• Undirected graph
• Directed graph
• Weighted graph
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU.
▪ Shortest-paths Problem
1. Single-source:
Find a shortest path from a given source vertex to each of the other vertices. This paradigm also works
for the single-destination shortest path problem. By reversing the direction of each edge in the graph, we can
reduce this problem to a single-source problem.
2. Single-pair:
Given 2 vertices, find a shortest path between them. Solution to single-source problem solves this
problem efficiently, too.
3. All-pairs:
Find shortest-paths for every pair of vertices.
▪ Single-source shortest path problem: Given a graph 𝐺 = (𝑉, 𝐸) with weight function 𝑤: 𝐸 → ℝ and a source vertex
𝑠 ∈ 𝑉, find for all vertices 𝑣 ∈ 𝑉 the minimum possible weight for path from 𝑠 to 𝑣.
Different Algorithms:
• Breadth-first search (BFS) – If all the edge weights are equal.
• Dijkstra – If all the edge weights are positive.
• Bellman-Ford – If all the edge weights are positive and negative.
1. Breadth-first search (BFS) – 𝑂(|𝑉| + |𝐸|)
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU.
Algorithm:
2. Bellman-ford – 𝑂(|𝑉||𝐸|)
BFS(G, s)
1. for each vertex 𝑢 in V[G] – {s}
2. color[u]  white
3. d[u]  
4. [u]  nil
5. color[s]  gray
6. d[s]  0
7. [s]  nil
8. Q  
9. enqueue(Q, s)
10. while Q  
11. u  dequeue(Q)
12. for each v in Adj[u]
13. if color[v] = white
14. color[v]  gray
15. d[v]  d[u] + 1
16. [v]  u
17. enqueue(Q, v)
18. color[u]  black
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU.
Algorithm:
3. Dijkstra’s algorithm – min-priority queue: Array 𝑂(|𝑉|2
),
Binary heap 𝑂(|𝐸| lg (|𝑉|)),
Fibonacci heap 𝑂(|𝑉| lg(|𝑉|) + |𝐸|)
BELLMAN-FORD(V, E, w, s)
1. INITIALIZE-SINGLE-SOURCE(V, s)
2. for i ← 1 to |V| - 1
3. do for each edge (u, v)  E
4. do RELAX(u, v, w)
5. for each edge (u, v)  E
6. do if d[v] > d[u] + w(u, v)
7. then return FALSE
8. return TRUE
INITIALIZE-SINGLE-SOURCE(V, s)
1. for each v  V
2. do d[v] ← 
3. [v] ← NIL
4. d[s] ← 0
RELAX(u, v, w)
1. if d[v] > d[u] + w(u, v)
2. then d[v] ← d[u] + w(u, v)
3. [v] ← u
Negative Cycle Detection
This section detects negative cycle. If
exists then the algorithm will return False
otherwise True.
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU.
Algorithm
C++ STL – Priority Queue
#include <iostream>
#include <queue>
#include <vector>
#include <functional> ///for greater function
using namespace std;
class mycomp{
public:
bool operator()(const pair<int,int> &elm1, const pair<int,int> &elm2){
return elm1.second>elm2.second;
}
};
int main()
{
priority_queue<int> pq; ///default max heap
pq.push(10);
pq.push(-5);
pq.push(8);
pq.push(2);
pq.push(4);
while(!pq.empty()){
cout<< pq.top() <<" ";
pq.pop();
}
cout<<endl;
///------------------------------------------------------------------------
priority_queue<int, vector<int>, greater<int> > pq1; ///use as min heap
pq1.push(10);
pq1.push(-5);
pq1.push(8);
DIJKSTRA(G, w, s)
1. INITIALIZE-SINGLE-SOURCE(V, s)
2. S ← 
3. Q ← V[G]
4. while Q  
5. do u ← EXTRACT-MIN(Q)
6. S ← S  {u}
7. for each vertex v  Adj[u]
8. do RELAX(u, v, w)
INITIALIZE-SINGLE-SOURCE(V, s)
1. for each v  V
2. do d[v] ← 
3. [v] ← NIL
4. d[s] ← 0
RELAX(u, v, w)
1. if d[v] > d[u] + w(u, v)
2. then d[v] ← d[u] + w(u, v)
3. [v] ← u
4. also update the Priority Queue
value
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU.
pq1.push(2);
pq1.push(4);
while(!pq1.empty()){
cout<< pq1.top() <<" ";
pq1.pop();
}
cout<<endl;
///------------------------------------------------------------------------
priority_queue< pair<int, int>, vector< pair<int,int> >, mycomp > pq2; ///use as min
heap
pair<int,int> p1(10,8);
pair<int,int> p2(5,10);
pair<int,int> p3(9,18);
pair<int,int> p4(2,7);
pair<int,int> p5(9,5);
pq2.push(p1);
pq2.push(p2);
pq2.push(p3);
pq2.push(p4);
pq2.push(p5);
while(!pq2.empty()){
cout<<"("<<pq2.top().first <<" "<<pq2.top().second<<")"<<" ";
pq2.pop();
}
cout<<endl;
return 0;
}

More Related Content

Similar to DS & Algo 4 - Graph and Shortest Path Search

TechMathI - 3.1 - Lines in Space Day2
TechMathI - 3.1 - Lines in Space Day2TechMathI - 3.1 - Lines in Space Day2
TechMathI - 3.1 - Lines in Space Day2lmrhodes
 
Unsymmetrical bending (2nd year)
Unsymmetrical bending (2nd year)Unsymmetrical bending (2nd year)
Unsymmetrical bending (2nd year)Alessandro Palmeri
 
GRAPH - DISCRETE STRUCTURE AND ALGORITHM
GRAPH - DISCRETE STRUCTURE AND ALGORITHMGRAPH - DISCRETE STRUCTURE AND ALGORITHM
GRAPH - DISCRETE STRUCTURE AND ALGORITHMhimanshumishra19dec
 
Application of particle swarm optimization in 3 dimensional travelling salesm...
Application of particle swarm optimization in 3 dimensional travelling salesm...Application of particle swarm optimization in 3 dimensional travelling salesm...
Application of particle swarm optimization in 3 dimensional travelling salesm...Maad M. Mijwil
 
Kakuro: Solving the Constraint Satisfaction Problem
Kakuro: Solving the Constraint Satisfaction ProblemKakuro: Solving the Constraint Satisfaction Problem
Kakuro: Solving the Constraint Satisfaction ProblemVarad Meru
 
Centroid and Moment of Inertia from mechanics of material by hibbler related ...
Centroid and Moment of Inertia from mechanics of material by hibbler related ...Centroid and Moment of Inertia from mechanics of material by hibbler related ...
Centroid and Moment of Inertia from mechanics of material by hibbler related ...FREE LAUNCER
 
graphinglinearequations-111002175614-phpapp02 (1).pptx
graphinglinearequations-111002175614-phpapp02 (1).pptxgraphinglinearequations-111002175614-phpapp02 (1).pptx
graphinglinearequations-111002175614-phpapp02 (1).pptxkristinebua
 
TIU CET Review Math Session 6 - part 2 of 2
TIU CET Review Math Session 6 - part 2 of 2TIU CET Review Math Session 6 - part 2 of 2
TIU CET Review Math Session 6 - part 2 of 2youngeinstein
 
Introduction to Finite Element Analysis
Introduction to Finite Element Analysis Introduction to Finite Element Analysis
Introduction to Finite Element Analysis Madhan N R
 
Engineering Mechanice Lecture 05
Engineering Mechanice Lecture 05Engineering Mechanice Lecture 05
Engineering Mechanice Lecture 05Self-employed
 
MA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docx
MA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docxMA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docx
MA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docxinfantsuk
 

Similar to DS & Algo 4 - Graph and Shortest Path Search (20)

TechMathI - 3.1 - Lines in Space Day2
TechMathI - 3.1 - Lines in Space Day2TechMathI - 3.1 - Lines in Space Day2
TechMathI - 3.1 - Lines in Space Day2
 
DAA_Presentation - Copy.pptx
DAA_Presentation - Copy.pptxDAA_Presentation - Copy.pptx
DAA_Presentation - Copy.pptx
 
Unsymmetrical bending (2nd year)
Unsymmetrical bending (2nd year)Unsymmetrical bending (2nd year)
Unsymmetrical bending (2nd year)
 
NN-Ch3.PDF
NN-Ch3.PDFNN-Ch3.PDF
NN-Ch3.PDF
 
GRAPH - DISCRETE STRUCTURE AND ALGORITHM
GRAPH - DISCRETE STRUCTURE AND ALGORITHMGRAPH - DISCRETE STRUCTURE AND ALGORITHM
GRAPH - DISCRETE STRUCTURE AND ALGORITHM
 
Application of particle swarm optimization in 3 dimensional travelling salesm...
Application of particle swarm optimization in 3 dimensional travelling salesm...Application of particle swarm optimization in 3 dimensional travelling salesm...
Application of particle swarm optimization in 3 dimensional travelling salesm...
 
Kakuro: Solving the Constraint Satisfaction Problem
Kakuro: Solving the Constraint Satisfaction ProblemKakuro: Solving the Constraint Satisfaction Problem
Kakuro: Solving the Constraint Satisfaction Problem
 
Centroid and Moment of Inertia from mechanics of material by hibbler related ...
Centroid and Moment of Inertia from mechanics of material by hibbler related ...Centroid and Moment of Inertia from mechanics of material by hibbler related ...
Centroid and Moment of Inertia from mechanics of material by hibbler related ...
 
graphinglinearequations-111002175614-phpapp02 (1).pptx
graphinglinearequations-111002175614-phpapp02 (1).pptxgraphinglinearequations-111002175614-phpapp02 (1).pptx
graphinglinearequations-111002175614-phpapp02 (1).pptx
 
Poster KH & SH
Poster KH & SHPoster KH & SH
Poster KH & SH
 
TIU CET Review Math Session 6 - part 2 of 2
TIU CET Review Math Session 6 - part 2 of 2TIU CET Review Math Session 6 - part 2 of 2
TIU CET Review Math Session 6 - part 2 of 2
 
Introduction to Finite Element Analysis
Introduction to Finite Element Analysis Introduction to Finite Element Analysis
Introduction to Finite Element Analysis
 
Algebreviewer
AlgebreviewerAlgebreviewer
Algebreviewer
 
Algebreviewer
AlgebreviewerAlgebreviewer
Algebreviewer
 
Curve fitting
Curve fittingCurve fitting
Curve fitting
 
Curve fitting
Curve fittingCurve fitting
Curve fitting
 
Engineering Mechanice Lecture 05
Engineering Mechanice Lecture 05Engineering Mechanice Lecture 05
Engineering Mechanice Lecture 05
 
Teknik Simulasi
Teknik SimulasiTeknik Simulasi
Teknik Simulasi
 
MA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docx
MA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docxMA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docx
MA 243 Calculus III Fall 2015 Dr. E. JacobsAssignmentsTh.docx
 
NN-Ch3 (1).ppt
NN-Ch3 (1).pptNN-Ch3 (1).ppt
NN-Ch3 (1).ppt
 

More from Mohammad Imam Hossain

DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionMohammad Imam Hossain
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaMohammad Imam Hossain
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaMohammad Imam Hossain
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckMohammad Imam Hossain
 

More from Mohammad Imam Hossain (20)

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
 
DS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic ProgrammingDS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic Programming
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL Introduction
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
 
TOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal FormTOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal Form
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 

DS & Algo 4 - Graph and Shortest Path Search

  • 1. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. ▪ Graph: A graph 𝐺 = (𝑉, 𝐸) consists of two sets, 𝑉 = set of vertices (nodes) 𝐸 = set of edges = subset of (𝑉 × 𝑉) ▪ Representation 1. Adjacency Matrix: • Undirected graph 1 2 3 4 5 6 [ 0 1 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0] • Weighted undirected graph 1 2 3 4 5 6 [ ∞ 5 ∞ ∞ 11 ∞ 5 ∞ ∞ ∞ 6 ∞ ∞ ∞ ∞ ∞ ∞ 10.5 ∞ ∞ ∞ ∞ ∞ ∞ 11 6 ∞ ∞ ∞ ∞ ∞ ∞ 10.5 ∞ ∞ ∞ ] • Directed graph 1 2 3 4 5 6 [ 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0] • Weighted directed graph 1 2 3 4 5 6 [ ∞ 7.8 ∞ ∞ ∞ ∞ ∞ ∞ ∞ 11 8.1 ∞ ∞ ∞ ∞ ∞ ∞ ∞ 7.6 ∞ ∞ ∞ 9 ∞ ∞ ∞ ∞ 8.8 ∞ ∞ ∞ ∞ 12 ∞ ∞ ∞] 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6
  • 2. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. 2. Adjacency List: • Undirected graph • Directed graph • Weighted graph
  • 3. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. ▪ Shortest-paths Problem 1. Single-source: Find a shortest path from a given source vertex to each of the other vertices. This paradigm also works for the single-destination shortest path problem. By reversing the direction of each edge in the graph, we can reduce this problem to a single-source problem. 2. Single-pair: Given 2 vertices, find a shortest path between them. Solution to single-source problem solves this problem efficiently, too. 3. All-pairs: Find shortest-paths for every pair of vertices. ▪ Single-source shortest path problem: Given a graph 𝐺 = (𝑉, 𝐸) with weight function 𝑤: 𝐸 → ℝ and a source vertex 𝑠 ∈ 𝑉, find for all vertices 𝑣 ∈ 𝑉 the minimum possible weight for path from 𝑠 to 𝑣. Different Algorithms: • Breadth-first search (BFS) – If all the edge weights are equal. • Dijkstra – If all the edge weights are positive. • Bellman-Ford – If all the edge weights are positive and negative. 1. Breadth-first search (BFS) – 𝑂(|𝑉| + |𝐸|)
  • 4. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Algorithm: 2. Bellman-ford – 𝑂(|𝑉||𝐸|) BFS(G, s) 1. for each vertex 𝑢 in V[G] – {s} 2. color[u]  white 3. d[u]   4. [u]  nil 5. color[s]  gray 6. d[s]  0 7. [s]  nil 8. Q   9. enqueue(Q, s) 10. while Q   11. u  dequeue(Q) 12. for each v in Adj[u] 13. if color[v] = white 14. color[v]  gray 15. d[v]  d[u] + 1 16. [v]  u 17. enqueue(Q, v) 18. color[u]  black
  • 5. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Algorithm: 3. Dijkstra’s algorithm – min-priority queue: Array 𝑂(|𝑉|2 ), Binary heap 𝑂(|𝐸| lg (|𝑉|)), Fibonacci heap 𝑂(|𝑉| lg(|𝑉|) + |𝐸|) BELLMAN-FORD(V, E, w, s) 1. INITIALIZE-SINGLE-SOURCE(V, s) 2. for i ← 1 to |V| - 1 3. do for each edge (u, v)  E 4. do RELAX(u, v, w) 5. for each edge (u, v)  E 6. do if d[v] > d[u] + w(u, v) 7. then return FALSE 8. return TRUE INITIALIZE-SINGLE-SOURCE(V, s) 1. for each v  V 2. do d[v] ←  3. [v] ← NIL 4. d[s] ← 0 RELAX(u, v, w) 1. if d[v] > d[u] + w(u, v) 2. then d[v] ← d[u] + w(u, v) 3. [v] ← u Negative Cycle Detection This section detects negative cycle. If exists then the algorithm will return False otherwise True.
  • 6. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Algorithm C++ STL – Priority Queue #include <iostream> #include <queue> #include <vector> #include <functional> ///for greater function using namespace std; class mycomp{ public: bool operator()(const pair<int,int> &elm1, const pair<int,int> &elm2){ return elm1.second>elm2.second; } }; int main() { priority_queue<int> pq; ///default max heap pq.push(10); pq.push(-5); pq.push(8); pq.push(2); pq.push(4); while(!pq.empty()){ cout<< pq.top() <<" "; pq.pop(); } cout<<endl; ///------------------------------------------------------------------------ priority_queue<int, vector<int>, greater<int> > pq1; ///use as min heap pq1.push(10); pq1.push(-5); pq1.push(8); DIJKSTRA(G, w, s) 1. INITIALIZE-SINGLE-SOURCE(V, s) 2. S ←  3. Q ← V[G] 4. while Q   5. do u ← EXTRACT-MIN(Q) 6. S ← S  {u} 7. for each vertex v  Adj[u] 8. do RELAX(u, v, w) INITIALIZE-SINGLE-SOURCE(V, s) 1. for each v  V 2. do d[v] ←  3. [v] ← NIL 4. d[s] ← 0 RELAX(u, v, w) 1. if d[v] > d[u] + w(u, v) 2. then d[v] ← d[u] + w(u, v) 3. [v] ← u 4. also update the Priority Queue value
  • 7. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. pq1.push(2); pq1.push(4); while(!pq1.empty()){ cout<< pq1.top() <<" "; pq1.pop(); } cout<<endl; ///------------------------------------------------------------------------ priority_queue< pair<int, int>, vector< pair<int,int> >, mycomp > pq2; ///use as min heap pair<int,int> p1(10,8); pair<int,int> p2(5,10); pair<int,int> p3(9,18); pair<int,int> p4(2,7); pair<int,int> p5(9,5); pq2.push(p1); pq2.push(p2); pq2.push(p3); pq2.push(p4); pq2.push(p5); while(!pq2.empty()){ cout<<"("<<pq2.top().first <<" "<<pq2.top().second<<")"<<" "; pq2.pop(); } cout<<endl; return 0; }