[LeetCode] Find the Degree of Each Vertex

3898. Find the Degree of Each Vertex

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.

  • matrix[i][j] = 1 indicates that there is an edge between vertices i and j.
  • matrix[i][j] = 0 indicates that there is no edge between vertices i and j.

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.

1
2
3
4
5
6
7
8
9
class Solution {
public:
vector<int> findDegrees(vector<vector<int>>& matrix) {
int n = matrix.size();
vector<int> res(n);
for(int i = 0; i < n; i++) res[i] = accumulate(begin(matrix[i]), end(matrix[i]), 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/find-the-degree-of-each-vertex/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.