Advertisement
fueanta

Adjacency Matrix and Adjacency Graph

Dec 4th, 2016
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. // adjacency matrix and adjacency list
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. void adjacency_matrix(int**, int);
  7. void adjacency_list(int**, int);
  8. void show_matrix(int**, int);
  9. void show_list(int**, int);
  10.  
  11. int main() {
  12.     cout << "How many vertices ? Number of Vertices: ";
  13.     int number, **arr1, **arr2; cin >> number;
  14.  
  15.     arr1 = new int*[number]; // mamory allocation for n pointers
  16.     adjacency_matrix(arr1, number); // input taken
  17.     show_matrix(arr1, number); // show adjacency matrix
  18.  
  19.     cout << "\nAdjacency Matrix to List: " << endl;
  20.     show_list(arr1, number);
  21.  
  22.     arr2 = new int*[number]; // mamory allocation for n pointers [for a different array]
  23.     adjacency_list(arr2, number); // input taken
  24.     show_list(arr2, number); // show adjacency list
  25.  
  26.     cout << "\nAdjacency List to Matrix: " << endl;
  27.     show_matrix(arr2, number);
  28.  
  29.     cout << endl;
  30.     return 0;
  31. }
  32.  
  33. void adjacency_matrix(int **arr, int n) {
  34.     cout << "\nGIVE YOUR MATRIX INPUT: [ " << n << " col. and rows ]" << endl;
  35.     for (int i = 0; i < n; i++) {
  36.         arr[i] = new int[n]; // memory allocation for n int(s) for each row
  37.         for (int j = 0; j < n; j++) {
  38.             cin >> arr[i][j];
  39.         }
  40.     }
  41. }
  42.  
  43. void adjacency_list(int **arr, int n) {
  44.     cout << "\nGIVE ADJACENT VERTICES FOR EACH VERTEX: " << endl;
  45.     for (int i = 0; i < n; i++) {
  46.         arr[i] = new int[n]; // memory allocation for n int(s) for each row
  47.         for (int j = 0; j < n; j++)
  48.             arr[i][j] = 0;
  49.         cout << "\nTotal Vertices for " << i + 1 << ": "; int x; cin >> x;
  50.         cout << "\nAdjacent Vertices: ";
  51.         for (int j = 0; j < x; j++) {
  52.             int m; cin >> m;
  53.             arr[i][m - 1] = 1;
  54.         }
  55.     }
  56. }
  57.  
  58. void show_matrix(int **arr, int n) {
  59.     cout << "\nAdjacency matrix: " << endl;
  60.     for (int i = 0; i < n; i++) {
  61.         for (int j = 0; j < n; j++) {
  62.             cout << arr[i][j] << " ";
  63.         }
  64.         cout << endl;
  65.     }
  66. }
  67.  
  68. void show_list(int **arr, int n) {
  69.     cout << "\nAdjacency list: " << endl;
  70.     for (int i = 0; i < n; i++) {
  71.         cout << i + 1 << " -> ";
  72.         for (int j = 0; j < n; j++) {
  73.             if (arr[i][j] == 1)
  74.                 cout << j + 1 << " ";
  75.         }
  76.         cout << endl;
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement