Leetcode Note: Go - Matrix Diagonal Sum
Matrix Diagonal Sum - LeetCode
https://leetcode.com/problems/matrix-diagonal-sum/
- Go 言語で取り組んだメモ
回答
Python/JS/Java/Go/C++ O(n) by iteration [w/ Comment] - Matrix Diagonal Sum - LeetCode
https://leetcode.com/problems/matrix-diagonal-sum/solutions/837795/python-js-java-go-c-o-n-by-iteration-w-comment/
func diagonalSum(mat [][]int) int {
// side-length
n := len(mat)
// mid point index
mid := n / 2
// summation of diagonal element
summation := 0
for i := 0 ; i < n ; i++{
// primary diagonal
summation += mat[i][i]
// secondary diagonal
summation += mat[n-1-i][i]
}
if n % 2 == 1 {
// remove center element (repeated) on odd side-length case
summation -= mat[mid][mid]
}
return summation
}