main.cpp 904 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include<stdio.h>
  2. #define V 4
  3. void addEdge(int mat[V][V], int i, int j) {
  4. mat[i][j] = 1;
  5. mat[j][i] = 1; // Since the graph is undirected
  6. }
  7. void displayMatrix(int mat[V][V]) {
  8. for (int i = 0; i < V; i++) {
  9. for (int j = 0; j < V; j++)
  10. printf("%d ", mat[i][j]);
  11. printf("\n");
  12. }
  13. }
  14. int main() {
  15. // Create a graph with 4 vertices and no edges
  16. // Note that all values are initialized as 0
  17. int mat[V][V] = {0};
  18. // Now add edges one by one
  19. addEdge(mat, 0, 1);
  20. addEdge(mat, 0, 2);
  21. addEdge(mat, 1, 2);
  22. addEdge(mat, 2, 3);
  23. /* Alternatively, we can also create using the below
  24. code if we know all edges in advance
  25. int mat[V][V] = {
  26. {0, 1, 0, 0},
  27. {1, 0, 1, 0},
  28. {0, 1, 0, 1},
  29. {0, 0, 1, 0}
  30. }; */
  31. printf("Adjacency Matrix Representation\n");
  32. displayMatrix(mat);
  33. return 0;
  34. }