Adjacency list representation of graph (nodes with string names, Hashing)
#include<bits/stdc++.h>
using namespace std;
class graph{
/*creating a hash map,
<string><list of pair(<string,weight>)>
A-> B 20, C 30
B-> A 20, D 40
C-> D 10
D-> B 40, C 10
*/
public:
unordered_map<string, list<pair<string,int>>>mp;
void addEdge(string x,string y, bool is_bidir, int wght)
{
mp[x].push_back(make_pair(y,wght));
if(is_bidir==true)
mp[y].push_back(make_pair(x,wght));
}
/*void print()
{
for(auto it=mp.begin();it!=mp.end();it++)
{
//Here, there is a pointer which is pointing to every member index,
//hence use arrow operator,
cout<<it->first<<"-> ";
for(auto it2=it->second.begin(); it2!=it->second.end(); it2++)
cout<<it2->first<<" "<<it2->second<<",";
cout<<endl;
}
}or*/
void print()
{
for(auto it: mp)
{
/*every hash member consists of two parts
"string" and "list of pairs" so, store string in
one varaible and take copy of that list
into another general list l;*/
string node=it.first;
/*auto it:mp, in this "it" refers to every
combined member value, hence use dot operator,*/
list<pair<string,int>> list_at_node=it.second;
cout<<node<<"-> ";
//now travesre the list;
for(auto it2: list_at_node)
{
cout<<it2.first<<" "<<it2.second<<", ";
}
cout<<endl;
}
}
};
int main()
{
graph g;
g.addEdge("A","B",true,20);
g.addEdge("B","D",true,30);
g.addEdge("C","D",true,40);
g.addEdge("A","C",true,10);
g.addEdge("A","D",false,50);
g.print();
}
Comments
Post a Comment