main.cpp 893 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. // Function to add an edge between two vertices
  5. void addEdge(vector<vector<int>>& adj, int i, int j) {
  6. adj[i].push_back(j);
  7. adj[j].push_back(i); // Undirected
  8. }
  9. // Function to display the adjacency list
  10. void displayAdjList(const vector<vector<int>>& adj) {
  11. for (int i = 0; i < adj.size(); i++) {
  12. cout << i << ": "; // Print the vertex
  13. for (int j : adj[i]) {
  14. cout << j << " "; // Print its adjacent
  15. }
  16. cout << endl;
  17. }
  18. }
  19. // Main function
  20. int main() {
  21. // Create a graph with 4 vertices and no edges
  22. int V = 4;
  23. vector<vector<int>> adj(V);
  24. // Now add edges one by one
  25. addEdge(adj, 0, 1);
  26. addEdge(adj, 0, 2);
  27. addEdge(adj, 1, 2);
  28. addEdge(adj, 2, 3);
  29. cout << "Adjacency List Representation:" << endl;
  30. displayAdjList(adj);
  31. return 0;
  32. }