pranay_teja
9/15/2018 - 9:56 AM

Graphs Adjacency list

#include<bits/stdc++.h>
using namespace std;

// #Graphs #BasicProblem
//	https://practice.geeksforgeeks.org/problems/print-adjacency-list/0

int main(){
    int t;
    cin>>t;
    while(t--){
        int v;
    	// cout<<"no of vertices ?"<<endl;
    	cin>>v;
    	vector< vector<int> > AdjL(v);
    	int e;
    	// cout<<"no of edges ?"<<endl;
    	cin>>e;
    	int i=0;
    	while(i<e){
    	    int a,b;
    	    // cout<<"Enter connections \n example: 2 3 (edge b/w 2nd and 3rd node)"<<endl;
    	    cin>>a>>b;
    	    // Undirected graph => edge entries in both vertices
    	    AdjL[a].push_back(b);
    	    AdjL[b].push_back(a);
    	    i++;
    	}
    	//cout<<"Adjacency List:"<<endl;
    	for(int j=0;j<v;j++){
    	    cout<<j;
    	    if(AdjL[j].size()!=0){
    	        cout<<"-> ";
    	    }
    	    for(int k=0;k<AdjL[j].size();k++){
    	        cout<<AdjL[j][k];
    	        if(k<AdjL[j].size()-1){
    	            cout<<"-> ";
    	        }
    	    }
    	    cout<<endl;
    	}
    }
    return 0;
}