|
| 1 | +/** |
| 2 | +
|
| 3 | + * @file |
| 4 | + * @brief Demonstrates how to create a graph using Adjacency list representation. |
| 5 | + * @details Takes user input to create either a directed or undirected graph. |
| 6 | + * Include input validation and prints the final graph structure. |
| 7 | +
|
| 8 | +*/ |
| 9 | + |
| 10 | +#include <iostream> |
| 11 | +#include <vector> |
| 12 | + |
| 13 | +using namespace std; |
| 14 | + |
| 15 | +//Graph class |
| 16 | + |
| 17 | +class Graph{ |
| 18 | + |
| 19 | +private: |
| 20 | + int V; |
| 21 | + vector<vector<int>> adj; |
| 22 | + bool directed; |
| 23 | + |
| 24 | +public: |
| 25 | + Graph(int V, bool directed ){ |
| 26 | + this->V = V; |
| 27 | + this->directed = directed; |
| 28 | + adj.resize(V); |
| 29 | + } |
| 30 | + void addEdge(int from , int to){ |
| 31 | + if(from>=V || to>=V || from<0 || to<0){ //Checking if given vertices are inside the bound of (0-[V-1]). |
| 32 | + cout<<"Error: vertex out of bound!!!\n"; |
| 33 | + return; |
| 34 | + } |
| 35 | + adj[from].push_back(to); |
| 36 | + if(directed == false ) |
| 37 | + adj[to].push_back(from); |
| 38 | + } |
| 39 | + |
| 40 | + void printGraph() { |
| 41 | + cout<<"The Graph Representation by Adjacency List:\n"; |
| 42 | + for(int i=0 ; i<V ; i++){ |
| 43 | + cout<<"Node "<<i<<": "; |
| 44 | + for(int adjacentNode : adj[i]) |
| 45 | + cout<<adjacentNode<< " "; |
| 46 | + cout<<endl; |
| 47 | + } |
| 48 | + } |
| 49 | +}; |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +int main() |
| 54 | +{ |
| 55 | + int V; |
| 56 | + do{ |
| 57 | + |
| 58 | + cout<<"Enter number of Nodes in the Graph:"; |
| 59 | + cin>>V; |
| 60 | + cin.ignore(); |
| 61 | + if(V>INT_MAX || V<1) // Checking to limit the input size between [0 - INT_MAX] |
| 62 | + cout<<"Enter a valid positive number!!\n"; |
| 63 | + }while(V>INT_MAX || V<1); |
| 64 | + |
| 65 | + /*----Whether the Graph will be directed or not----*/ |
| 66 | + int isDirected; |
| 67 | + |
| 68 | + do{ |
| 69 | + cout<<"Is this graph directed (0=No , 1=Yes):"; |
| 70 | + cin>>isDirected; |
| 71 | + }while(isDirected != 0 && isDirected !=1); |
| 72 | + |
| 73 | + Graph g(V,isDirected); //Initializing the Graph object. |
| 74 | + |
| 75 | + /*----Creating edges of the graph----*/ |
| 76 | + cout<<"Create edges (enter pairs of connected nodes):\n"; |
| 77 | + int addMore; |
| 78 | + do{ |
| 79 | + int from , to; |
| 80 | + cout<<"From Node:"; |
| 81 | + cin>>from; |
| 82 | + cout<<"To Node :"; |
| 83 | + cin>>to; |
| 84 | + g.addEdge(from ,to); |
| 85 | + cout << "Do you want to add another edge? (1 = yes, 0 = no): "; |
| 86 | + cin>>addMore; // A flag value to let user decided when to stop. |
| 87 | + }while(addMore>0); |
| 88 | + |
| 89 | + cout<<"\nGraph creation complete.\n"; |
| 90 | + g.printGraph(); //To Print the created graph of V nodes. |
| 91 | + |
| 92 | + return 0; |
| 93 | +} |
0 commit comments