Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

REPRESENTATION OF GRAPHS

ADJACENCY MATRIX REPRESENTATION


Aim:
To write a C++ program to represent the given graph using its adjacency matrix.

Algorithm:
Step 1 : Start

Step 2 : Declare a 2D integer array of size 20.

Step 3 : Create a display function to display the adjacency matrix in matrix form.

Step 4 : Create a function to represent the vertices and add the edges with two integer parameters.

Step 5 : Add the cost between the connecting edges as 1 else add 0.

Step 6 : Declare the number of vertices and add the edges with cost =1 using add_edge function.

Step 7 : Display the adjacency matrix

Step 8 : Stop.

Program:
#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]<<"\t";

cout<<endl;

void add_edge(int u,int v)

vertarr[u][v]=1;

vertarr[v][u]=1;

int main(int argc,char* argv[])

int v=5;

add_edge(0,1);

add_edge(0,4);

add_edge(1,0);

add_edge(1,2);

add_edge(1,3);

add_edge(1,4);

add_edge(2,1);

add_edge(2,3);

add_edge(3,1);

add_edge(3,2);

add_edge(3,4);

add_edge(4,1);

add_edge(4,3);

displaymatrix(v);
return 0;

Output:

ADJACENCY LIST REPRESENTATION


Aim:
To write a C++ program to represent the given graph using its adjacency list

Algorithm:
Step 1 : Start

Step 2 : Create a function to display the adjacency list in the list form.

Step 3 : Create a list of integers and create an iterator for it.

Step 4 : Using the iterator , print its adjacent vertices.

Step 5 : Create a function add_edges to add create the edges between the two vertices.

Step 6 : Declare the number of edges in the given graph in a variable v.

Step 7 : Using the add_edges function , find the edges from a vertex adjacent to it.
Step 8 : Use the display function to represent the adjacency list form.

Step 9 : Stop.

Program:
#include<iostream>

#include<list>

#include<iterator>

using namespace std;

void displayAdjList(list<int> adj_list[], int v) {

for(int i = 0; i<v; i++) {

cout << i << "--->";

list<int> :: iterator it;

for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {

cout << *it << " ";

cout << endl;

void add_edge(list<int> adj_list[], int u, int v) {

adj_list[u].push_back(v);

adj_list[v].push_back(u);

int main(int argc, char* argv[]) {

int v = 6;

list<int> adj_list[v];

add_edge(adj_list, 0, 4);

add_edge(adj_list, 0, 3);

add_edge(adj_list, 1, 2);

add_edge(adj_list, 1, 4);

add_edge(adj_list, 1, 5);

add_edge(adj_list, 2, 3);

add_edge(adj_list, 2, 5);
add_edge(adj_list, 5, 3);

add_edge(adj_list, 5, 4);

displayAdjList(adj_list, v);

return 0;

Output:

You might also like