LeetCode-in-Java

3898. Find the Degree of Each Vertex

Easy

You are given a 2D integer array matrix of size n x n representing the adjacency matrix of an undirected graph with n vertices labeled from 0 to n - 1.

The degree of a vertex is the number of edges connected to it.

Return an integer array ans of size n where ans[i] represents the degree of vertex i.

Example 1:

Input: matrix = [[0,1,1],[1,0,1],[1,1,0]]

Output: [2,2,2]

Explanation:

Thus, the answer is [2, 2, 2].

Example 2:

Input: matrix = [[0,1,0],[1,0,0],[0,0,0]]

Output: [1,1,0]

Explanation:

Thus, the answer is [1, 1, 0].

Example 3:

Input: matrix = [[0]]

Output: [0]

Explanation:

There is only one vertex and it has no edges connected to it. Thus, the answer is [0].

Constraints:

Solution

public class Solution {
    public int[] findDegrees(int[][] matrix) {
        int[] res = new int[matrix.length];
        int n1 = matrix.length;
        int n2 = matrix[0].length;
        for (int i = 0; i < n1; i++) {
            int sum = 0;
            for (int j = 0; j < n2; j++) {
                sum += matrix[i][j];
            }
            res[i] = sum;
        }
        return res;
    }
}