Experiment No 7
Experiment No 7
//RA2311043010090
#include <iostream>
#include <vector>
using namespace std;
class Graph {
private:
int numVertices;
vector<vector<int>> adjacencyMatrix;
public:
Graph(int n) : numVertices(n) {
adjacencyMatrix.resize(n, vector<int>(n, 0));
}
void addEdge(int from, int to) {
if (from >= 0 && from < numVertices && to >= 0 && to < numVertices) {
adjacencyMatrix[from][to] = 1;
adjacencyMatrix[to][from] = 1; // Uncomment if graph is undirected
} else {
cout << "Invalid edge!\n";
}
}
void display() {
for (int i = 0; i < numVertices; ++i) {
for (int j = 0; j < numVertices; ++j) {
cout << adjacencyMatrix[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
Graph graph(4);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(1, 2);
cout << "Adjacency Matrix:\n";
graph.display();
return 0;
}
Output:
Program 2: Write a C++ program to create an adjacency matrix representation for the
graphshown in fig 1.
//RA2311043010090
#include <iostream>
#include <list>
#include <vector>
using namespace std;
class Graph {
private:
int numVertices;
vector<list<int>> adjacencyList;
public:
Graph(int n) : numVertices(n) {
adjacencyList.resize(n); }
void addEdge(int from, int to) {
adjacencyList[from].push_back(to);
adjacencyList[to].push_back(from); }
void display() {
for (int i = 0; i < numVertices; ++i) {
cout << "Vertex " << i << " -> ";
for (int neighbor : adjacencyList[i]) {
cout << neighbor << " "; }
cout << endl;
}}};
int main() {
Graph graph(4);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(1, 2);
cout << "Adjacency List:\n";
graph.display();
return 0;}
Post lab questions :
1. In a simple graph, the number of edges is equal to twice the sum of the degrees of the
vertices. a) True b) False