python 🐍 | Solution with Explanation !!
\nPlatform: leetcode.com\n1572. Matrix Diagonal Sum\nLink: https://leetcode.com/problems/matrix-diagonal-sum/\nDifficulty: Easy\nAuthor: hritik5102\nDate: 30/1/
```\nPlatform: leetcode.com\n1572. Matrix Diagonal Sum\nLink: https://leetcode.com/problems/matrix-diagonal-sum/\nDifficulty: Easy\nAuthor: hritik5102\nDate: 30/1/2021\nSubmission: https://leetcode.com/submissions/detail/449645959\nPost Discussion : https://leetcode.com/problems/matrix-diagonal-sum/discuss/1041736\n\n(Time, Space) Complexity : O(n), O(n)\n```\n\n# Method 01 : Easy to understand \n\n1. Find row, column of the matrix\n2. initilize the total = 0\n3. Add all diagonal matrix \n\nAll diagonal element, which has **odd** numbers of **row** and **column**\n```\n                0 1 2    \n            0 [[1,2,3],\n            1  [4,5,6],\n            2  [7,8,9]]\n```\n\ntotal = total + mat[0][0] + mat[0][2] = 0 + 1 + 3 = 4 \ntotal = total + mat[1][1] + mat[1][1] = 4 + 5 + 5 = 14  \ntotal = total + mat[2][2] + mat[2][0] = 14 + 9 + 7 = 29 \n\nNotice that element mat[1][1] = 5 is counted only once.\n\nSo we substract total with that element i.e. = total - mat[1][1]\n\n**Answer** = 29 - 5 = 25\n\nSimilarly if it\'s a **even** size matrix , we don\'t have any common part, we simply return **total**  \n\n```python\nclass Solution:\n    def diagonalSum(self, mat):\n        row,col,total = len(mat),len(mat[0]),0\n        for i in range(row):\n            total+=mat[i][i]+mat[i][col-i-1]\n        return total-mat[row//2][col//2] if row%2!=0 else total\n```\n# Method 2: As it\'s a square matrix (Equal numbers of row and column)\n\nSo don\'t need to calculate length of column. \n\n```python\nclass Solution:\n    def diagonalSum(self, mat):\n        row,total = len(mat),0\n        for i in range(row):\n            total+=mat[i][i]+mat[i][row-i-1]\n        return total-mat[row//2][row//2] if row%2!=0 else total\n\n\nobj = Solution()\nprint(obj.diagonalSum(mat = [[1,2,3],\n                              [4,5,6],\n                              [7,8,9]]))\n```\n\nPLEASE UPVOTE \uD83D\uDC4D , if found helpful :)
['Python']