Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // adjacency matrix and adjacency list
- #include <iostream>
- using namespace std;
- void adjacency_matrix(int**, int);
- void adjacency_list(int**, int);
- void show_matrix(int**, int);
- void show_list(int**, int);
- int main() {
- cout << "How many vertices ? Number of Vertices: ";
- int number, **arr1, **arr2; cin >> number;
- arr1 = new int*[number]; // mamory allocation for n pointers
- adjacency_matrix(arr1, number); // input taken
- show_matrix(arr1, number); // show adjacency matrix
- cout << "\nAdjacency Matrix to List: " << endl;
- show_list(arr1, number);
- arr2 = new int*[number]; // mamory allocation for n pointers [for a different array]
- adjacency_list(arr2, number); // input taken
- show_list(arr2, number); // show adjacency list
- cout << "\nAdjacency List to Matrix: " << endl;
- show_matrix(arr2, number);
- cout << endl;
- return 0;
- }
- void adjacency_matrix(int **arr, int n) {
- cout << "\nGIVE YOUR MATRIX INPUT: [ " << n << " col. and rows ]" << endl;
- for (int i = 0; i < n; i++) {
- arr[i] = new int[n]; // memory allocation for n int(s) for each row
- for (int j = 0; j < n; j++) {
- cin >> arr[i][j];
- }
- }
- }
- void adjacency_list(int **arr, int n) {
- cout << "\nGIVE ADJACENT VERTICES FOR EACH VERTEX: " << endl;
- for (int i = 0; i < n; i++) {
- arr[i] = new int[n]; // memory allocation for n int(s) for each row
- for (int j = 0; j < n; j++)
- arr[i][j] = 0;
- cout << "\nTotal Vertices for " << i + 1 << ": "; int x; cin >> x;
- cout << "\nAdjacent Vertices: ";
- for (int j = 0; j < x; j++) {
- int m; cin >> m;
- arr[i][m - 1] = 1;
- }
- }
- }
- void show_matrix(int **arr, int n) {
- cout << "\nAdjacency matrix: " << endl;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- cout << arr[i][j] << " ";
- }
- cout << endl;
- }
- }
- void show_list(int **arr, int n) {
- cout << "\nAdjacency list: " << endl;
- for (int i = 0; i < n; i++) {
- cout << i + 1 << " -> ";
- for (int j = 0; j < n; j++) {
- if (arr[i][j] == 1)
- cout << j + 1 << " ";
- }
- cout << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement