VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-graph-given-degrees-vertices/

⇱ Construct a graph from given degrees of all vertices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct a graph from given degrees of all vertices

Last Updated : 31 Jan, 2023

This is a C++ program to generate a graph for a given fixed degree sequence. This algorithm generates a undirected graph for the given degree sequence.It does not include self-edge and multiple edges.

Examples: 

Input : degrees[] = {2, 2, 1, 1}
Output : (0) (1) (2) (3)
 (0) 0 1 1 0 
 (1) 1 0 0 1 
 (2) 1 0 0 0 
 (3) 0 1 0 0 
Explanation : We are given that there
are four vertices with degree of vertex
0 as 2, degree of vertex 1 as 2, degree
of vertex 2 as 1 and degree of vertex 3
as 1. Following is graph that follows
given conditions. 
 (0)----------(1)
 | | 
 | | 
 | |
 (2) (3) 

Approach : 

  1. Take the input of the number of vertexes and their corresponding degree. 
  2. Declare adjacency matrix, mat[ ][ ] to store the graph. 
  3. To create the graph, create the first loop to connect each vertex ā€˜i’. 
  4. Second nested loop to connect the vertex ā€˜i’ to the every valid vertex ā€˜j’, next to it. 
  5. If the degree of vertex ā€˜i’ and ā€˜j’ are more than zero then connect them. 
  6. Print the adjacency matrix.

Based on the above explanation, below are implementations:


Output
 (0) (1) (2) (3) (4)

 (0) 0 1 1 0 0
 (1) 1 0 0 1 0
 (2) 1 0 0 0 0
 (3) 0 1 0 0 0
 (4) 0 0 0 0 0

Time Complexity: O(v*v).

Space complexity : O(n^2) because it creates a 2-dimensional array (matrix) of size n * n, where n is the number of vertices in the graph.

Comment
Article Tags:
Article Tags: