fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<vector<int>> adjacencyMatrix(51, vector<int>(51, 0));
  5. vector<vector<int>> adjacencyList(51);
  6.  
  7. // Hardcoded graph
  8. int nodes = 5;
  9. int edges = 4;
  10. pair<int, int> edgeList[] = {
  11. {1, 2},
  12. {1, 3},
  13. {2, 4},
  14. {4, 5}
  15. };
  16.  
  17. // Function declarations
  18. void inputMatrix();
  19. void inputList();
  20. void printMatrix();
  21. void printList();
  22.  
  23. int main() {
  24. // Build both representations
  25. inputMatrix();
  26. inputList();
  27.  
  28. // Print adjacency matrix
  29. printMatrix();
  30.  
  31. // Print adjacency list
  32. printList();
  33.  
  34. return 0;
  35. }
  36.  
  37. // Build adjacency matrix from hardcoded edges
  38. void inputMatrix() {
  39. for(int i = 0; i < edges; i++) {
  40. int u = edgeList[i].first;
  41. int v = edgeList[i].second;
  42. adjacencyMatrix[u][v] = 1;
  43. adjacencyMatrix[v][u] = 1; // Remove this line for directed graph
  44. }
  45. }
  46.  
  47. // Build adjacency list from hardcoded edges
  48. void inputList() {
  49. for(int i = 0; i < edges; i++) {
  50. int u = edgeList[i].first;
  51. int v = edgeList[i].second;
  52. adjacencyList[u].push_back(v);
  53. adjacencyList[v].push_back(u); // Remove this line for directed graph
  54. }
  55. }
  56.  
  57. // Print adjacency matrix
  58. void printMatrix() {
  59. cout << "Adjacency Matrix:\n";
  60. for(int i = 1; i <= nodes; i++) {
  61. for(int j = 1; j <= nodes; j++) {
  62. cout << adjacencyMatrix[i][j] << " ";
  63. }
  64. cout << endl;
  65. }
  66. cout << endl;
  67. }
  68.  
  69. // Print adjacency list
  70. void printList() {
  71. cout << "Adjacency List:\n";
  72. for(int i = 1; i <= nodes; i++) {
  73. cout << i << ": ";
  74. for(int v : adjacencyList[i]) {
  75. cout << v << " ";
  76. }
  77. cout << endl;
  78. }
  79. }
  80.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Adjacency Matrix:
0 1 1 0 0 
1 0 0 1 0 
1 0 0 0 0 
0 1 0 0 1 
0 0 0 1 0 

Adjacency List:
1: 2 3 
2: 1 4 
3: 1 
4: 2 5 
5: 4