Skip to main content

Represent a graph using adjacency matrix / Represent a graph using adjacency list.

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;

}









Popular posts from this blog

Write a program to create a class Student2 along with two method getData (), printData () to get the value through argument and display the data in printData. Create the two objects s1, s2 to declare and access the values from class STtest.

 CODE: import java.util.Scanner; class Student2 {     private String name;     private int age;          // Method to set data     public void getData(String name, int age) {         this.name = name;         this.age = age;     }          // Method to print data     public void printData() {         System.out.println("Name: " + name);         System.out.println("Age: " + age);     } } public class STtest {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);                  // Creating objects of Student2 class         Student2 s1 = new Student2();         Student2 s2 = new Student2();              ...