简体   繁体   中英

Adjacency list representation using vector of vectors(2D vector) in C++

We can fill adjacency list in BFS using 1D vector like vector<int> adj[10];<\/code> we can fill that vector as follows:

main(){
int x,y,nodes,edges;
cin>>nodes>>edges;
for(int i=0;i<edges;i++){
cin>>x>>y;
adj[x].push_back(y); //Insert y in adjacency list of x
}
}

Say, maximum value of x could be n .
First you have to initialize the 2D vector with n number of 1D vector.
Then you can perform the operations like you did in your example.

vector<vector<int> >g;
for(int i = 0; i<n; i++)
{
    vector<int>v;
    g.push_back(v);
}

g[0].push_back(3);
g[1].push_back(5);
cout<<g[0][0]<<endl;
cout<<g[1][0]<<endl;

Or you can initialize the vector at the time of declaring.

vector<vector<int> >g(n);

g[0].push_back(3);
g[1].push_back(5);
cout<<g[0][0]<<endl;
cout<<g[1][0]<<endl;

vector<vector> g(nodes, vector());

g[1].push_back(5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM