Find the Degree of Each Vertex
Intuition #
The degree of a vertex is the number of edges connected to it, and matrix[i][j] is either 1 for connected or 0 for not connected.
We are tasked to return the number of edges connected to i, and the sum of matrix[i] is the number of edges connected to i.
Approach #
- Initialize
resultof type[]int. - Loop (
i) overmatrix:- Loop (
j) overmatrix[i]:- Add
matrix[i][j]toresult[i].
- Add
- Loop (
- Return
result.
Complexity #
Time complexity: .
- We visit every cell once.
Space complexity: .
resultcontains elements.
Code #
1func findDegrees(matrix [][]int) []int {
2 result := make([]int, len(matrix))
3
4 for i := range matrix {
5 for j := range matrix[i] {
6 result[i] += matrix[i][j]
7 }
8 }
9
10 return result
11}