fork download
  1. // C++ program to demonstrate Adjacency Matrix
  2. // representation of undirected and unweighted graph
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. void addEdge(vector<vector<int>> &mat, int i, int j)
  7. {
  8. mat[i][j] = 1;
  9. mat[j][i] = 1; // Since the graph is undirected
  10. }
  11.  
  12. void displayMatrix(vector<vector<int>> &mat)
  13. {
  14. int V = mat.size();
  15. for (int i = 0; i < V; i++)
  16. {
  17. for (int j = 0; j < V; j++)
  18. cout << mat[i][j] << " ";
  19. cout << endl;
  20. }
  21. }
  22.  
  23. int main()
  24. {
  25.  
  26. // Create a graph with 4 vertices and no edges
  27. // Note that all values are initialized as 0
  28. int V = 4;
  29. vector<vector<int>> mat(V, vector<int>(V, 0));
  30.  
  31. // Now add edges one by one
  32. addEdge(mat, 0, 1);
  33. addEdge(mat, 0, 2);
  34. addEdge(mat, 1, 2);
  35. addEdge(mat, 2, 3);
  36.  
  37. /* Alternatively we can also create using below
  38.   code if we know all edges in advacem
  39.  
  40.   vector<vector<int>> mat = {{ 0, 1, 0, 0 },
  41.   { 1, 0, 1, 0 },
  42.   { 0, 1, 0, 1 },
  43.   { 0, 0, 1, 0 } }; */
  44.  
  45. cout << "Adjacency Matrix Representation" << endl;
  46. displayMatrix(mat);
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
Adjacency Matrix Representation
0 1 1 0 
1 0 1 0 
1 1 0 1 
0 0 1 0