Just Iteration - Explained
First, let\'s break this problem into two sub-problems - calculate the the sum of primary diagonal and the sum of secondary diagonal. \n\nIn the primary diagona
First, let\'s break this problem into two sub-problems - calculate the the sum of primary diagonal and the sum of secondary diagonal. \n\nIn the primary diagonal, the row number equals to the column number, so it is pretty straightforward to get the numbers on the primary diagonal. \n\nIn the secondary diagonal, the column number decreases as row number increases, and you should be able to obtain the relation `col = len(mat) - row - 1`. \n\nWe also have to be mindful to avoid computing the element at `mat[len(mat)//2][len(mat)//2]` twice, so we add a conditional check to skip if it exists. Note that this does not always exist (if the dimension of the matrix is two even numbers - See Example 1 and 2)\n\n```py\nclass Solution:\n    def diagonalSum(self, mat: List[List[int]]) -> int:\n        n = len(mat)\n        res = 0\n\t\t# sub-problem #1\n        # add all values in primary diagonal\n        for row in range(n):\n            # col = row in primary diagonal\n            col = row \n            # add the value to result\n            res += mat[row][col]\n\t\t# sub-problem #2\n        # add all values in secondary diagonal\n        for row in range(n):\n            # col is the the opposite end of row in secondary diagonal\n            col = n - row - 1\n\t\t\t# handle special case\n            # to avoid adding the center number twice, we skip if row == col\n            if row == col: continue\n            # add the value to result\n            res += mat[row][col]\n        return res\n```\n\nOnce you get the idea, we can put all the logic into a single iteration. Hene, we can simplify as below\n\n```py\nclass Solution:\n    def diagonalSum(self, mat: List[List[int]]) -> int:\n        n = len(mat)\n        res = 0\n        for row in range(n):\n            # primary diagonal\n            # col = row in primary diagonal\n            res += mat[row][row]\n            # seconday diagonal\n            # col is the the opposite end of row in secondary diagonal\n            res += mat[row][n - 1 - row]\n        if n & 1:\n            # to avoid adding the center number twice\n            res -= mat[n // 2][n // 2]\n        return res\n```
['Python']