Graph Theory(adjacency matrix,adjacency list)
today I will speak about one of the
most important topics which are graph theory.
I will take a long time in this
series because I wanna speak a lot of data structure related to graph theory
but in the beginning, I will speak
about just two representations which are
(adjacency matrix, adjacency list).
adjacency matrix
the first let's talk about adjacency matrix .this to make a memory representation for any graph
(directed or non-directed) we can imagine that
Like
code
bool adjacency_matrix[100][100];
Example
n=3
0 1 0
1 1 0
0 1 1
for(int i=0;i<n;i++)
for(int j=0;j<;j++){
int x;
cin>>x;
adjacency_matrix[i][j]=x;
}
adjacency list
then I will speak about adjacency list, how to represent it in memory and how we implement it with code
code
vector< vector<int> > adjList1; if adjacency list without weight
vector< vector< pair<int, int> > > adjList2; if adjacency list with weight
Example-1
3
2 1 2
1 2
2 0 1
cin>>n;
adjList1 = vector< vector<int> >(n);
for(i=0;i< n; i++)
{
int cnt;
cin>>cnt;
for( j=0; j< cnt;j++)
{
int to;
cin>>to;
adjList1[i].push_back(to);
}
}
Example-2
3
2 1 13 2 4
1 2 9 3 -4
2 0 -7 1 8
cin>>n;
adjList2 = vector< vector< pair<int, int> > >(n);
for(int i=0;i< n;i++)
{
int cnt;
cin>>cnt;
for(int j=0; j< cnt;j++)
{
int to, cost;
cin>>to>>cost;
adjList2[i].push_back( make_pair(to, cost));
}
}
Comments
Post a Comment