Open In App

Construct a graph from given degrees of all vertices

Last Updated : 31 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ program to generate a graph for a
// given fixed degrees
#include <bits/stdc++.h>
using namespace std;
 
// A function to print the adjacency matrix.
void printMat(int degseq[], int n)
{
    // n is number of vertices
    int mat[n][n];
    memset(mat, 0, sizeof(mat));
 
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // For each pair of vertex decrement
            // the degree of both vertex.
            if (degseq[i] > 0 && degseq[j] > 0) {
                degseq[i]--;
                degseq[j]--;
                mat[i][j] = 1;
                mat[j][i] = 1;
            }
        }
    }
 
    // Print the result in specified format
    cout << "\n"
         << setw(3) << "     ";
    for (int i = 0; i < n; i++)
        cout << setw(3) << "(" << i << ")";
    cout << "\n\n";
    for (int i = 0; i < n; i++) {
        cout << setw(4) << "(" << i << ")";
        for (int j = 0; j < n; j++)
            cout << setw(5) << mat[i][j];
        cout << "\n";
    }
}
 
// driver program to test above function
int main()
{
    int degseq[] = { 2, 2, 1, 1, 1 };
    int n = sizeof(degseq) / sizeof(degseq[0]);
    printMat(degseq, n);
    return 0;
}


Java




// Java program to generate a graph for a
// given fixed degrees
import java.util.*;
 
class GFG
{
 
// A function to print the adjacency matrix.
static void printMat(int degseq[], int n)
{
    // n is number of vertices
    int [][]mat = new int[n][n];
 
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
 
            // For each pair of vertex decrement
            // the degree of both vertex.
            if (degseq[i] > 0 && degseq[j] > 0)
            {
                degseq[i]--;
                degseq[j]--;
                mat[i][j] = 1;
                mat[j][i] = 1;
            }
        }
    }
 
    // Print the result in specified format
    System.out.print("\n" + setw(3) + "     ");
     
    for (int i = 0; i < n; i++)
        System.out.print(setw(3) + "(" + i + ")");
    System.out.print("\n\n");
    for (int i = 0; i < n; i++)
    {
        System.out.print(setw(4) + "(" + i + ")");
         
        for (int j = 0; j < n; j++)
            System.out.print(setw(5) + mat[i][j]);
        System.out.print("\n");
    }
}
 
static String setw(int n)
{
    String space = "";
    while(n-- > 0)
        space += " ";
    return space;
}
 
// Driver Code
public static void main(String[] args)
{
    int degseq[] = { 2, 2, 1, 1, 1 };
    int n = degseq.length;
    printMat(degseq, n);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to generate a graph
# for a given fixed degrees
 
# A function to print the adjacency matrix.
def printMat(degseq, n):
     
    # n is number of vertices
    mat = [[0] * n for i in range(n)]
 
    for i in range(n):
        for j in range(i + 1, n):
 
            # For each pair of vertex decrement
            # the degree of both vertex.
            if (degseq[i] > 0 and degseq[j] > 0):
                degseq[i] -= 1
                degseq[j] -= 1
                mat[i][j] = 1
                mat[j][i] = 1
 
    # Print the result in specified form
    print("      ", end = " ")
    for i in range(n):
        print(" ", "(", i, ")", end = "")
    print()
    print()
    for i in range(n):
        print(" ", "(", i, ")", end = "")
        for j in range(n):
            print("     ", mat[i][j], end = "")
        print()
 
# Driver Code
if __name__ == '__main__':
    degseq = [2, 2, 1, 1, 1]
    n = len(degseq)
    printMat(degseq, n)
 
# This code is contributed by PranchalK


C#




// C# program to generate a graph for a
// given fixed degrees
using System;
     
class GFG
{
 
// A function to print the adjacency matrix.
static void printMat(int []degseq, int n)
{
    // n is number of vertices
    int [,]mat = new int[n, n];
 
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
 
            // For each pair of vertex decrement
            // the degree of both vertex.
            if (degseq[i] > 0 && degseq[j] > 0)
            {
                degseq[i]--;
                degseq[j]--;
                mat[i, j] = 1;
                mat[j, i] = 1;
            }
        }
    }
 
    // Print the result in specified format
    Console.Write("\n" + setw(3) + "     ");
     
    for (int i = 0; i < n; i++)
        Console.Write(setw(3) + "(" + i + ")");
    Console.Write("\n\n");
    for (int i = 0; i < n; i++)
    {
        Console.Write(setw(4) + "(" + i + ")");
         
        for (int j = 0; j < n; j++)
            Console.Write(setw(5) + mat[i, j]);
        Console.Write("\n");
    }
}
 
static String setw(int n)
{
    String space = "";
    while(n-- > 0)
        space += " ";
    return space;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []degseq = { 2, 2, 1, 1, 1 };
    int n = degseq.Length;
    printMat(degseq, n);
}
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// JavaScript program to generate a graph for a
// given fixed degrees
 
// A function to print the adjacency matrix.
function printMat(degseq,n)
{
    // n is number of vertices
    let mat = new Array(n);
    for(let i=0;i<n;i++)
    {
        mat[i]=new Array(n);
        for(let j=0;j<n;j++)
            mat[i][j]=0;
    }
   
    for (let i = 0; i < n; i++)
    {
        for (let j = i + 1; j < n; j++)
        {
   
            // For each pair of vertex decrement
            // the degree of both vertex.
            if (degseq[i] > 0 && degseq[j] > 0)
            {
                degseq[i]--;
                degseq[j]--;
                mat[i][j] = 1;
                mat[j][i] = 1;
            }
        }
    }
   
    // Print the result in specified format
    document.write("<br>" + setw(3) + "     ");
       
    for (let i = 0; i < n; i++)
        document.write(setw(3) + "(" + i + ")");
    document.write("<br><br>");
    for (let i = 0; i < n; i++)
    {
        document.write(setw(4) + "(" + i + ")");
           
        for (let j = 0; j < n; j++)
            document.write(setw(5) + mat[i][j]);
        document.write("<br>");
    }
}
 
function setw(n)
{
    let space = "";
    while(n-- > 0)
        space += " ";
    return space;
}
 
// Driver Code
let degseq=[2, 2, 1, 1, 1];
let n = degseq.length;
printMat(degseq, n);
 
// This code is contributed by rag2127
 
</script>


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.



Previous Article
Next Article

Similar Reads

Construct a graph using N vertices whose shortest distance between K pair of vertices is 2
Given two positive integers N and K, the task is to construct a simple and connected graph consisting of N vertices with the length of each edge as 1 unit, such that the shortest distance between exactly K pairs of vertices is 2. If it is not possible to construct the graph, then print -1. Otherwise, print the edges of the graph. Examples: Input: N
7 min read
Finding in and out degrees of all vertices in a graph
Given a directed graph, the task is to count the in and out degree of each vertex of the graph. Examples: Input: Output: Vertex In Out 0 1 2 1 2 1 2 2 3 3 2 2 4 2 2 5 2 2 6 2 1 Approach: Traverse adjacency list for every vertex, if size of the adjacency list of vertex i is x then the out degree for i = x and increment the in degree of every vertex
9 min read
Check whether given degrees of vertices represent a Graph or Tree
Given the number of vertices and the degree of each vertex where vertex numbers are 1, 2, 3,...n. The task is to identify whether it is a graph or a tree. It may be assumed that the graph is Connected. Examples: Input : 5 2 3 1 1 1 Output : Tree Explanation : The input array indicates that vertex one has degree 2, vertex two has degree 3, vertices
5 min read
Find K vertices in the graph which are connected to at least one of remaining vertices
Given a connected graph with N vertices. The task is to select k(k must be less than or equals to n/2, not necessarily minimum) vertices from the graph such that all these selected vertices are connected to at least one of the non selected vertex. In case of multiple answers print any one of them. Examples: Input : Output : 1 Vertex 1 is connected
8 min read
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph
Pre-requisites: Handshaking theorem. Pendant Vertices Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. Note: Degree = number of edges connected to a vertex In the case of trees, a pendant vertex is known as a
7 min read
Number of trees whose sum of degrees of all the vertices is L
Given an integer L which is the sum of degrees of all the vertices of some tree. The task is to find the count of all such distinct trees (labeled trees). Two trees are distinct if they have at least a single different edge.Examples: Input: L = 2 Output: 1Input: L = 6 Output: 16 Recommended: Please try your approach on {IDE} first, before moving on
13 min read
Maximize the sum of products of the degrees between any two vertices of the tree
Given an integer N, the task is to construct a tree such that the sum of [Tex]degree(u) * degree(v) [/Tex]for all ordered pairs (u, v) is the maximum where u != v. Print the maximum possible sum. Examples: Input: N = 4 Output: 26 1 / 2 / 3 / 4 For node 1, 1*2 + 1*2 + 1*1 = 5 For node 2, 2*1 + 2*2 + 2*1 = 8 For node 3, 2*1 + 2*2 + 2*1 = 8 For node 4
6 min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
Find the remaining vertices of a square from two given vertices
Given the coordinates of any two vertices of a square (X1, Y1) and (X2, Y2), the task is to find the coordinates of the other two vertices. If a square cannot be formed using these two vertices, print -1. Examples: Input: X1 = 1, Y1 = 2, X2 = 3, Y2 = 4 Output: (1, 4), (3, 2) Explanation: From the above figure the other two vertices of the square wi
6 min read
Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
Given a tree with N vertices numbered 1 through N with vertex 1 as root vertex and N - 1 edges. We have to color exactly k number of vertices and count the number of uncolored vertices between root vertex and every colored vertex. We have to include the root vertex in the count if it is not colored. The task to maximize the number of uncolored vert
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg