SlideShare a Scribd company logo
IMPLEMENTATION OF
GRAPHS
RAYYAN NAEEM
2024PAI7303
ADJACENCY MATRIX
• Definition:An adjacency matrix is a 2D array (or matrix) of sizeVxV, whereV is the
number of vertices in the graph.
• Matrix Content : If there is an edge between vertices i and j, matrix[i][j] = 1 (for
unweighted graphs) or the weight of the edge (for weighted graphs).If there is no edge,
matrix[i][j] = 0.
Implementation of graphs, adjaceny matrix
#include <iostream>
#include <vector>
using namespace std;
class graph{
private:
int n;
vector<vector<int>> adj_matrix;
public:
graph(int num):n(num),adj_matrix(n,vector<int>(n,0)){}
void add_edge(int u, int v)
{
if(u>=0 && u<n && v>=0 && v<n)
{
adj_matrix[u][v]=1;
adj_matrix[v][u]=1;
}
}
void print_matrix()
{
for(int i=0;i<n;i++)
{ for(int j=0;j<n;j++)
{
cout<<adj_matrix[i][j]<<"t";
}
cout<<endl;}}
};
int main()
{
int x,a,b;
cout <<"enter the number of vertices = "; cin>>x;
graph g(x);
for(int i=0;i<x;i++)
{
cout <<"n enter the edge=";
cin>>a>>b;
g.add_edge(a,b);}
cout<<endl;
g.print_matrix();
return 0;
}
Implementation of graphs, adjaceny matrix
•Space Complexity: O(V²), whereV is the number of vertices.
•Memory Usage:
• Efficient for dense graphs (graphs where the number of edges is close
to the maximum number of edges, i.e.,V²).
• Inefficient for sparse graphs (graphs with fewer edges).
•Advantages:
• Simple and easy to implement.
• Quick lookup for edge existence between two vertices.
•Disadvantages:
• Requires O(V²) space, making it less efficient for sparse graphs.
• Iterating over all edges can take O(V²) time.
ADJACENCY LIST
• Definition: An adjacency list represents a graph as a collection of lists. Each vertex has a
list of its adjacent vertices.
• Structure:
• Each vertex points to a list containing its neighboring vertices.
• More memory-efficient than an adjacency matrix, especially for sparse graphs.
Implementation of graphs, adjaceny matrix
#include <iostream>
#include<list>
#include<map>
using namespace std;
class graph
{
map <int,list<int>> adjlist;
public:
void add_edge(int u,int v)
{
adjlist[u].push_back(v);
adjlist[v].push_back(u);
}
void display()
{
for(auto i: adjlist)
{
cout<<endl <<i.first << "->";
for(auto j: i.second)
{ cout<<j<<" ";
}}}};
int main()
{
graph g;
int a,b;
char x;
bool n=true;
while(n)
{
cout<<"n enter the edges=";
cin>>a>>b;
g.add_edge(a,b);
cout<<"do you want to enter more edges(y/n)=";
cin>>x;
if(x=='n')
n=false;
}
g.display();
return 0;
}
Implementation of graphs, adjaceny matrix
•Space Complexity: O(V + E), whereV is the number of vertices, and E is the number of
edges.More efficient than an adjacency matrix for sparse graphs.
•Advantages:
•More space-efficient for sparse graphs.
•Easier to iterate over neighbors of a vertex.
•Disadvantages:
•Slower edge lookups compared to an adjacency matrix (O(V)).
•Can become complex for weighted graphs.
SINGLE SOURCE SHORTEST PATH
What is Dijkstra’s Algorithm?
•Dijkstra's Algorithm is used to find the shortest path from a source vertex to all other vertices in
a weighted graph.
•Key Characteristics:
•Works with graphs that have non-negative weights.
•Greedy algorithm approach.
•Main Idea:
•Start from a source vertex and expand to its neighboring vertices.
•Keep track of the shortest known distance to each vertex.
•Update these distances as shorter paths are found using neighboring vertices.
•Greedy Approach:
•Always selects the unvisited vertex with the smallest known distance.
ALGORITHM
• 1. function Dijkstra(Graph, source):
• 2. dist[source] 0 // Distance from source to
←
source is 0
• 3. for each vertex v in Graph:
• 4. if v ≠ source:
• 5. dist[v] ∞ // Set all other distances to
←
infinity
• 6.add v to unvisited set
• 7. while unvisited set is not empty:
• 8. u vertex in unvisited set with smallest dist[u]
←
9. remove u from unvisited set
10. for each neighbor v of u:
11. alt dist[u] + length(u, v)
←
12. if alt < dist[v]:
13. dist[v] alt // Update distance if shorter path is
←
found
14. return dist[]
ALL PAIR SHORTEST PATH
Floyd-Warshall is an algorithm used to find the shortest paths between all pairs of vertices
in a weighted graph.
• Key Characteristics:
• Works for both directed and undirected graphs.
• Can handle graphs with negative edge weights, but no negative cycles.
•Main Idea:
•It uses a dynamic programming approach.
•It considers all pairs of vertices and iteratively improves the shortest path by including
intermediate vertices.
•Key Concept: If a path from vertex ito j through vertex k is shorter than the previously known
path from i to j, then update the path to pass through k.
ALGORITHM
• function FloydWarshall(dist[][]):
• for k from 1 to n:
• for i from 1 to n:
• for j from 1 to n:
• if dist[i][j] > dist[i][k] + dist[k][j]:
• dist[i][j] dist[i][k] + dist[k][j]
←
• return dist[][]
THANKYOU
Ad

More Related Content

Similar to Implementation of graphs, adjaceny matrix (20)

Graphs
GraphsGraphs
Graphs
Lakshmi Sarvani Videla
 
Dijkstra Shortest Path Algorithm in Network.ppt
Dijkstra Shortest Path Algorithm in Network.pptDijkstra Shortest Path Algorithm in Network.ppt
Dijkstra Shortest Path Algorithm in Network.ppt
RAJASEKARAN G
 
Dijkstra algorithm ds 57612334t4t44.ppt
Dijkstra algorithm  ds 57612334t4t44.pptDijkstra algorithm  ds 57612334t4t44.ppt
Dijkstra algorithm ds 57612334t4t44.ppt
ssuser7b9bda1
 
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
babanazar7204
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
meisamstar
 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
Dabbal Singh Mahara
 
Graph_data_structure_information_engineering.pptx
Graph_data_structure_information_engineering.pptxGraph_data_structure_information_engineering.pptx
Graph_data_structure_information_engineering.pptx
sahilpawar2426
 
Complete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdfComplete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdf
marketing413921
 
Dijkstra.ppt
Dijkstra.pptDijkstra.ppt
Dijkstra.ppt
Ruchika Sinha
 
Social network-analysis-in-python
Social network-analysis-in-pythonSocial network-analysis-in-python
Social network-analysis-in-python
Joe OntheRocks
 
Graph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxGraph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptx
asimshahzad8611
 
Unit 4-PartB of data design and algorithms
Unit 4-PartB of data design and algorithmsUnit 4-PartB of data design and algorithms
Unit 4-PartB of data design and algorithms
cartoongamingworld09
 
d
dd
d
jagdeeparora86
 
Dijkstra
DijkstraDijkstra
Dijkstra
jagdeeparora86
 
Please finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdfPlease finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdf
petercoiffeur18
 
Graphs
GraphsGraphs
Graphs
KomalPaliwal3
 
09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf
Prasanna David
 
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
Thejaka Amila Kanewala, Ph.D.
 
Fallsem2015 16 cp4194-13-oct-2015_rm01_graphs
Fallsem2015 16 cp4194-13-oct-2015_rm01_graphsFallsem2015 16 cp4194-13-oct-2015_rm01_graphs
Fallsem2015 16 cp4194-13-oct-2015_rm01_graphs
SnehilKeshari
 
Chap 6 Graph.ppt
Chap 6 Graph.pptChap 6 Graph.ppt
Chap 6 Graph.ppt
shashankbhadouria4
 
Dijkstra Shortest Path Algorithm in Network.ppt
Dijkstra Shortest Path Algorithm in Network.pptDijkstra Shortest Path Algorithm in Network.ppt
Dijkstra Shortest Path Algorithm in Network.ppt
RAJASEKARAN G
 
Dijkstra algorithm ds 57612334t4t44.ppt
Dijkstra algorithm  ds 57612334t4t44.pptDijkstra algorithm  ds 57612334t4t44.ppt
Dijkstra algorithm ds 57612334t4t44.ppt
ssuser7b9bda1
 
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
babanazar7204
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
meisamstar
 
Graph_data_structure_information_engineering.pptx
Graph_data_structure_information_engineering.pptxGraph_data_structure_information_engineering.pptx
Graph_data_structure_information_engineering.pptx
sahilpawar2426
 
Complete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdfComplete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdf
marketing413921
 
Social network-analysis-in-python
Social network-analysis-in-pythonSocial network-analysis-in-python
Social network-analysis-in-python
Joe OntheRocks
 
Graph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxGraph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptx
asimshahzad8611
 
Unit 4-PartB of data design and algorithms
Unit 4-PartB of data design and algorithmsUnit 4-PartB of data design and algorithms
Unit 4-PartB of data design and algorithms
cartoongamingworld09
 
Please finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdfPlease finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdf
petercoiffeur18
 
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
Thejaka Amila Kanewala, Ph.D.
 
Fallsem2015 16 cp4194-13-oct-2015_rm01_graphs
Fallsem2015 16 cp4194-13-oct-2015_rm01_graphsFallsem2015 16 cp4194-13-oct-2015_rm01_graphs
Fallsem2015 16 cp4194-13-oct-2015_rm01_graphs
SnehilKeshari
 

Recently uploaded (20)

Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Ad

Implementation of graphs, adjaceny matrix

  • 2. ADJACENCY MATRIX • Definition:An adjacency matrix is a 2D array (or matrix) of sizeVxV, whereV is the number of vertices in the graph. • Matrix Content : If there is an edge between vertices i and j, matrix[i][j] = 1 (for unweighted graphs) or the weight of the edge (for weighted graphs).If there is no edge, matrix[i][j] = 0.
  • 4. #include <iostream> #include <vector> using namespace std; class graph{ private: int n; vector<vector<int>> adj_matrix; public: graph(int num):n(num),adj_matrix(n,vector<int>(n,0)){} void add_edge(int u, int v) { if(u>=0 && u<n && v>=0 && v<n) { adj_matrix[u][v]=1; adj_matrix[v][u]=1; } } void print_matrix() { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<adj_matrix[i][j]<<"t"; } cout<<endl;}} }; int main() { int x,a,b; cout <<"enter the number of vertices = "; cin>>x; graph g(x); for(int i=0;i<x;i++) { cout <<"n enter the edge="; cin>>a>>b; g.add_edge(a,b);} cout<<endl; g.print_matrix(); return 0; }
  • 6. •Space Complexity: O(V²), whereV is the number of vertices. •Memory Usage: • Efficient for dense graphs (graphs where the number of edges is close to the maximum number of edges, i.e.,V²). • Inefficient for sparse graphs (graphs with fewer edges). •Advantages: • Simple and easy to implement. • Quick lookup for edge existence between two vertices. •Disadvantages: • Requires O(V²) space, making it less efficient for sparse graphs. • Iterating over all edges can take O(V²) time.
  • 7. ADJACENCY LIST • Definition: An adjacency list represents a graph as a collection of lists. Each vertex has a list of its adjacent vertices. • Structure: • Each vertex points to a list containing its neighboring vertices. • More memory-efficient than an adjacency matrix, especially for sparse graphs.
  • 9. #include <iostream> #include<list> #include<map> using namespace std; class graph { map <int,list<int>> adjlist; public: void add_edge(int u,int v) { adjlist[u].push_back(v); adjlist[v].push_back(u); } void display() { for(auto i: adjlist) { cout<<endl <<i.first << "->"; for(auto j: i.second) { cout<<j<<" "; }}}}; int main() { graph g; int a,b; char x; bool n=true; while(n) { cout<<"n enter the edges="; cin>>a>>b; g.add_edge(a,b); cout<<"do you want to enter more edges(y/n)="; cin>>x; if(x=='n') n=false; } g.display(); return 0; }
  • 11. •Space Complexity: O(V + E), whereV is the number of vertices, and E is the number of edges.More efficient than an adjacency matrix for sparse graphs. •Advantages: •More space-efficient for sparse graphs. •Easier to iterate over neighbors of a vertex. •Disadvantages: •Slower edge lookups compared to an adjacency matrix (O(V)). •Can become complex for weighted graphs.
  • 12. SINGLE SOURCE SHORTEST PATH What is Dijkstra’s Algorithm? •Dijkstra's Algorithm is used to find the shortest path from a source vertex to all other vertices in a weighted graph. •Key Characteristics: •Works with graphs that have non-negative weights. •Greedy algorithm approach. •Main Idea: •Start from a source vertex and expand to its neighboring vertices. •Keep track of the shortest known distance to each vertex. •Update these distances as shorter paths are found using neighboring vertices. •Greedy Approach: •Always selects the unvisited vertex with the smallest known distance.
  • 13. ALGORITHM • 1. function Dijkstra(Graph, source): • 2. dist[source] 0 // Distance from source to ← source is 0 • 3. for each vertex v in Graph: • 4. if v ≠ source: • 5. dist[v] ∞ // Set all other distances to ← infinity • 6.add v to unvisited set • 7. while unvisited set is not empty: • 8. u vertex in unvisited set with smallest dist[u] ← 9. remove u from unvisited set 10. for each neighbor v of u: 11. alt dist[u] + length(u, v) ← 12. if alt < dist[v]: 13. dist[v] alt // Update distance if shorter path is ← found 14. return dist[]
  • 14. ALL PAIR SHORTEST PATH Floyd-Warshall is an algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. • Key Characteristics: • Works for both directed and undirected graphs. • Can handle graphs with negative edge weights, but no negative cycles. •Main Idea: •It uses a dynamic programming approach. •It considers all pairs of vertices and iteratively improves the shortest path by including intermediate vertices. •Key Concept: If a path from vertex ito j through vertex k is shorter than the previously known path from i to j, then update the path to pass through k.
  • 15. ALGORITHM • function FloydWarshall(dist[][]): • for k from 1 to n: • for i from 1 to n: • for j from 1 to n: • if dist[i][j] > dist[i][k] + dist[k][j]: • dist[i][j] dist[i][k] + dist[k][j] ← • return dist[][]