fork download
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. // Number of vertices
  5. #define V 6
  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, 3);
  48. addEdge(adjMatrix, 0, 4);
  49. addEdge(adjMatrix, 1, 4);
  50. addEdge(adjMatrix, 1, 5);
  51. addEdge(adjMatrix, 1, 2);
  52. addEdge(adjMatrix, 2, 5);
  53. addEdge(adjMatrix, 2, 3);
  54. addEdge(adjMatrix, 3, 5);
  55. addEdge(adjMatrix, 4, 5);
  56.  
  57. cout << "Adjacency Matrix:" << endl;
  58. // Print the adjacency matrix
  59. printAdjMatrix(adjMatrix);
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 5264KB
stdin
Standard input is empty
stdout
Adjacency Matrix:
0 0 0 1 1 0 
0 0 1 0 1 1 
0 1 0 1 0 1 
1 0 1 0 0 1 
1 1 0 0 0 1 
0 1 1 1 1 0