fork download
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. // Number of vertices
  5. #define V 5
  6.  
  7. // Function to initialize the adjacency matrix
  8. void initAdjMatrix(int adjMatrix[V][V])
  9. {
  10. // Initialize all elements of the adjacency matrix to 0
  11. for (int i = 0; i < V; i++) {
  12. for (int j = 0; j < V; j++) {
  13. adjMatrix[i][j] = 0;
  14. }
  15. }
  16. }
  17.  
  18. // Function to add an edge to the graph
  19. void addEdge(int adjMatrix[V][V], int u, int v)
  20. {
  21. // Mark the edge between vertices u and v as 1
  22. adjMatrix[u][v] = 1;
  23. // For undirected graph, mark opposite edge as well
  24. adjMatrix[v][u] = 1;
  25. }
  26.  
  27. // Function to print the adjacency matrix
  28. void printAdjMatrix(int adjMatrix[V][V])
  29. {
  30. // Print the adjacency matrix
  31. for (int i = 0; i < V; i++) {
  32. for (int j = 0; j < V; j++) {
  33. cout << adjMatrix[i][j] << " ";
  34. }
  35. cout << endl;
  36. }
  37. }
  38.  
  39. int main()
  40. {
  41. int adjMatrix[V][V];
  42.  
  43. // Initialize the adjacency matrix
  44. initAdjMatrix(adjMatrix);
  45.  
  46. // Add edges to the graph
  47. addEdge(adjMatrix, 0,1);
  48. addEdge(adjMatrix, 1, 2);
  49. addEdge(adjMatrix, 2, 2);
  50. addEdge(adjMatrix, 0, 3);
  51. addEdge(adjMatrix, 3, 0);
  52. addEdge(adjMatrix, 4,3);
  53.  
  54. cout << "Adjacency Matrix:" << endl;
  55. // Print the adjacency matrix
  56. printAdjMatrix(adjMatrix);
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0s 5292KB
stdin
Standard input is empty
stdout
Adjacency Matrix:
0 1 0 1 0 
1 0 1 0 0 
0 1 1 0 0 
1 0 0 0 1 
0 0 0 1 0