Skip to main content

Construct adjacency list by using adjacency matrix in c++

C++ program for Construct adjacency list by using adjacency matrix. Here problem description and explanation.

// Include header file
#include <iostream>

#include <vector>

using namespace std;
/*
    C++ program for
    Construct adjacency list using adjacency matrix
*/
class Graph
{
	public: int vertices;
	vector < vector < int >> adgeList;
	Graph(vector < vector < int >> matrix)
	{
		// Set number of nodes
		this->vertices = matrix.size();
		// Create memory of adgeList of each vertice
		for (int i = 0; i < this->vertices; ++i)
		{
			this->adgeList.push_back(vector < int > ());
		}
		this->makeAdjacencyList(matrix);
	}
	// Convert into adjacency list
	void makeAdjacencyList(vector < vector < int >> matrix)
	{
		for (int i = 0; i < this->vertices; ++i)
		{
			for (int j = 0; j < this->vertices; ++j)
			{
				if (matrix[i][j] == 1)
				{
					this->addEdge(i, j);
				}
			}
		}
	}
	void addEdge(int u, int v)
	{
		if (u < 0 || u >= this->vertices || 
            v < 0 || v >= this->vertices)
		{
			return;
		}
		// Add node edge
		this->adgeList.at(u).push_back(v);
	}
	// Display graph nodes and edges
	void printGraph()
	{
		cout << "\n Graph Adjacency List ";
		for (int i = 0; i < this->vertices; ++i)
		{
			cout << " \n [" << i << "] :";
			// iterate edges of i node
			for (int j = 0; j < this->adgeList.at(i).size(); j++)
			{
				if (j != 0)
				{
					cout << " → ";
				}
				cout << " " << this->adgeList.at(i).at(j);
			}
		}
	}
};
int main()
{
	vector < vector < int >> matrix {
		{
			0 , 1 , 1 , 0 , 1
		} , {
			1 , 0 , 1 , 0 , 1
		} , {
			1 , 1 , 0 , 1 , 0
		} , {
			0 , 1 , 0 , 0 , 1
		} , {
			1 , 1 , 0 , 1 , 0
		}
	};
	Graph *g = new Graph(matrix);
	// Display graph element
	g->printGraph();
	return 0;
}

Output

 Graph Adjacency List
 [0] : 1 →  2 →  4
 [1] : 0 →  2 →  4
 [2] : 0 →  1 →  3
 [3] : 1 →  4
 [4] : 0 →  1 →  3




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment