|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | + |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// Template class to define a generic graph |
| 7 | +template <typename T> |
| 8 | +class Graph { |
| 9 | +public: |
| 10 | + // 2D vector to store the adjacency matrix |
| 11 | + vector<vector<int>> adjacencyMatrix; |
| 12 | + |
| 13 | + // Constructor to initialize the adjacency matrix |
| 14 | + Graph(int totalVertices) { |
| 15 | + // Initialize a square matrix of size totalVertices x totalVertices with zeros |
| 16 | + adjacencyMatrix = vector<vector<int>>(totalVertices, vector<int>(totalVertices, 0)); |
| 17 | + } |
| 18 | + |
| 19 | + // Function to add an edge to the graph |
| 20 | + void addEdge(T source, T destination, int weight = 1, bool isDirected = false) { |
| 21 | + // Add an edge from source to destination with the specified weight |
| 22 | + adjacencyMatrix[source][destination] = weight; |
| 23 | + |
| 24 | + // If the graph is undirected, also add the reverse edge |
| 25 | + if (!isDirected) |
| 26 | + adjacencyMatrix[destination][source] = weight; |
| 27 | + } |
| 28 | + |
| 29 | + // Function to print the adjacency matrix |
| 30 | + void printMatrix(int totalVertices) { |
| 31 | + // Loop through each row of the matrix |
| 32 | + for (int row = 0; row < totalVertices; row++) { |
| 33 | + // Loop through each column of the matrix |
| 34 | + for (int col = 0; col < totalVertices; col++) { |
| 35 | + // Print the value at the current cell (row, col) |
| 36 | + cout << adjacencyMatrix[row][col] << " "; |
| 37 | + } |
| 38 | + // Print a newline at the end of each row |
| 39 | + cout << endl; |
| 40 | + } |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +int main() { |
| 45 | + int totalVertices = 3; // Define the total number of vertices in the graph |
| 46 | + |
| 47 | + // Create a graph object with the specified number of vertices |
| 48 | + Graph<int> g(totalVertices); |
| 49 | + |
| 50 | + // Add directed edges to the graph |
| 51 | + g.addEdge(0, 1, 1, true); // Add edge from vertex 0 to vertex 1 with weight 1 |
| 52 | + g.addEdge(1, 2, 1, true); // Add edge from vertex 1 to vertex 2 with weight 1 |
| 53 | + g.addEdge(2, 0, 1, true); // Add edge from vertex 2 to vertex 0 with weight 1 |
| 54 | + |
| 55 | + // Print the adjacency matrix |
| 56 | + cout << "Adjacency Matrix:" << endl; |
| 57 | + g.printMatrix(totalVertices); |
| 58 | + |
| 59 | + return 0; |
| 60 | +} |
0 commit comments