Skip to content

Instantly share code, notes, and snippets.

@Ch-sriram
Created October 31, 2020 17:03
Show Gist options
  • Save Ch-sriram/6c1ba7f81fb2d4ae09bddcab85e5336a to your computer and use it in GitHub Desktop.
Save Ch-sriram/6c1ba7f81fb2d4ae09bddcab85e5336a to your computer and use it in GitHub Desktop.
Print Adjacency List [TC: O(V+E); SC: O(1)]
// Problem Link: https://practice.geeksforgeeks.org/problems/print-adjacency-list-1587115620/1/
// The Graph structure is as folows
// Function to print graph
// adj: array of vectors to represent graph
// V: number of vertices
void printGraph(vector<int> adj[], int V) {
for(int u = 0; u < V; ++u) {
if((int)adj[u].size() == 0) cout << u;
else cout << u << "-> ";
for(int v = 0; v < (int)adj[u].size(); ++v)
if(v + 1 == adj[u].size())
cout << adj[u][v];
else cout << adj[u][v] << "-> ";
cout << "\n";
}
}
void addEdge(vector<int> *adj, int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
int main() {
int t; cin >> t;
while(t--) {
int vertices, edges, u, v;
cin >> vertices >> edges;
// Initialize the graph: G(V, E) -> represented as G[u][v]
vector<int> G[vertices];
for(int i = 0; i < edges; ++i) {
cin >> u >> v;
addEdge(G, u, v);
}
printGraph(G, vertices) << "\n";
}
return 0;
}
@Ch-sriram
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment