CODE:
//Graph using adjacency matrix
#include<iostream>
using namespace std;
int vertArr[20][20];
int count = 0;
void displayMatrix(int v) {
int i, j;
for(i = 0; i < v; i++) {
for(j = 0; j < v; j++) {
cout<<vertArr[i][j]<<" ";
}
cout<<endl;
}
}
void add_edge(int u, int v) {
vertArr[u][v] = 1;
vertArr[v][u] = 1;
}
main(int argc, char* argv[]) {
int v = 6;
add_edge(0, 4);
add_edge(0, 3);
add_edge(1, 2);
add_edge(1, 4);
add_edge(1, 5);
add_edge(2, 3);
add_edge(2, 5);
add_edge(5, 3);
add_edge(5, 4);
displayMatrix(v);
}
//Graph using adjacency list
#include <iostream>
const int MAX_VERTICES = 100;
class Graph {
int numVertices;
int adjList[MAX_VERTICES][MAX_VERTICES];
int numNeighbors[MAX_VERTICES];
public:
Graph(int V) {
numVertices = V;
for (int i = 0; i < numVertices; ++i) {
numNeighbors[i] = 0;
for (int j = 0; j < numVertices; ++j) {
adjList[i][j] = 0;
}
}
}
void addEdge(int u, int v) {
adjList[u][numNeighbors[u]++] = v;
adjList[v][numNeighbors[v]++] = u;
}
void printAdjList() {
for (int i = 0; i < numVertices; ++i) {
std::cout << "Adjacency list of vertex " << i << ": ";
for (int j = 0; j < numNeighbors[i]; ++j) {
std::cout << adjList[i][j] << " ";
}
std::cout << std::endl;
}
}
};
int main() {
int numVertices = 5;
Graph graph(numVertices);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
graph.printAdjList();
return 0;
}