Skip to content
Related Articles
Construct a graph from given degrees of all vertices
• Difficulty Level : Medium
• Last Updated : 22 Oct, 2019

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)
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 ``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);``    ``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`

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).

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up