#include <bits/stdc++.h>
using namespace std;
// initialize a 51x51 vector with cell value of 0 for each cell
vector<vector<int>> adjacencyMatrix(51, vector<int>(51, 0));
// initialize a vector with 51 empty rows
vector<vector<int>> adjacencyList(51);
// Declare file stream so all functions can access it
ifstream file("input.txt");
int u, v;
void inputMatrix(int &nodes, int &edges);
void inputList(int &nodes, int &edges);
void printMatrix(int nodes);
void printList(int nodes);
int main(){
int input, nodes, edges;
cout << "Enter 1 or 2 based on your preference." << endl;
cout << "Option 1: If you want to store the graph to adjacency matrix." << endl;
cout << "Option 2: If you want to store the graph to adjacency list." << endl;
cout << "Enter your option (1/2): ";
while (cin >> input){
if (input != 1 && input != 2){
cout << "Invalid Input!!! try again." << endl;
cout << "Enter your option (1/2): ";
continue;
}
break;
}
// Check if file can be opened
if (!file){
cout << "Error opening file!" << endl;
return 0;
}
// Read total number of nodes and edges from file
file >> nodes >> edges;
if (input == 1){
inputMatrix(nodes, edges);
printMatrix(nodes);
}
else{
inputList(nodes, edges);
printList(nodes);
}
file.close();
return 0;
}
void inputMatrix(int &nodes, int &edges){
int count = 0;
// Read each edge (u, v) and update adjacency matrix
while (count < edges && file >> u >> v)
{
adjacencyMatrix[u][v] = 1;// edge from u to v
adjacencyMatrix[v][u] = 1;// edge from v to u
count++;
}
}
void inputList(int &nodes, int &edges){
int count = 0;
// Read each edge (u, v) and store in adjacency list
while (count < edges && file >> u >> v){
adjacencyList[u].push_back(v);
adjacencyList[v].push_back(u);
count++;
}
}
// Displays the adjacency matrix
void printMatrix(int nodes){
cout << "\nAdjacency Matrix :\n";
for(auto rowIt= adjacencyMatrix.begin()+1;rowIt!= adjacencyMatrix.begin()+1+nodes;++rowIt){
for(auto colIt= rowIt->begin()+1;colIt!= rowIt->begin()+1+nodes;++colIt){
cout << *colIt << " ";
}
cout << endl;
}
}
// Displays the adjacency list
void printList(int nodes){
cout << "\nAdjacency List:\n";
// Loop through each node and print its connections
for (int i = 1; i <= nodes; i++){
cout << "Node"<<" " << i<<" " << "connected to : ";
if (adjacencyList[i].empty()){
cout << "No connections";
}
else{
bool a = true; // for proper separator
for (int e : adjacencyList[i]){
if (!a){
cout << " , "; }// separator
cout << e;
a = false;
}
}
cout << endl;
}
}