Let's declare a linear array . In the cell we'll store the degree of vertex , which is equal to the number of ones in the -th row of the adjacency matrix.
In an undirected graph, each edge is counted twice: if is the adjacency matrix and there is an edge between vertices and , then m[i][j] = m[j][i] = 1). For each edge we increment by (when the edge is encountered, deg[j] will be incremented by ).
Example
The graph given in the example looks as follows:
Algorithm implementation
Let's declare an array to store the degrees of the vertices.
#define MAX 101
int deg[MAX];Read the number of vertices in the graph . Initialize the array.
scanf("%d",&n);
memset(deg,0,sizeof(deg));Read the adjacency matrix.
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
{If there is an edge between vertices and in the graph (the value is ), increment by one.
scanf("%d",&value);
if (value == 1) deg[i]++;
}Print the degrees of all the vertices in the graph.
for(i = 0; i < n; i++)
printf("%d\n",deg[i]);Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
int deg[] = new int[n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
int value = con.nextInt();
if (value == 1) deg[i]++;
}
for(int i = 0; i < n; i++)
System.out.println(deg[i]);
con.close();
}
} Python implementation
Read the number of vertices in the graph .
n = int(input())Initialize the adjacency matrix and the list of vertex degrees .
g = [[] for _ in range(n)]
deg = [0] * nRead the adjacency matrix.
for i in range(n):
g[i] = list(map(int, input().split()))Compute the degrees of the graph's vertices. The degree of vertex is equal to the sum of the elements in the -th row of the adjacency matrix .
for i in range(n):
deg[i] = sum(g[i])Print the degrees of all the vertices in the graph.
for i in range(n):
print(deg[i])