Given a square grid of integers grid, with as many rows as columns, return the sum of the cells on its diagonal: the cells that go from the top-left corner to the bottom-right corner.
A grid is a list of rows, and each row is a list of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right. A cell is on the diagonal when its row number and its column number are the same: row 0 and column 0, row 1 and column 1, and so on.
Example 1:
Input: grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output: 15 Explanation: The diagonal cells are 1, 5 and 9: 1 + 5 + 9 = 15.
Example 2:
Input: grid = [ [7] ] Output: 7 Explanation: A grid with one cell: that cell is the whole diagonal.
Example 3:
Input: grid = [ [-1, 2], [3, -4] ] Output: -5 Explanation: The diagonal cells are -1 and -4: -1 + (-4) = -5. The 2 and the 3 are not on the diagonal.
Constraints:
gridhasnrows andncolumns, withnat least 1.- Every value is an integer between -1000 and 1000; values can be negative.
Free plan: 30 tutor messages. Premium is unlimited.
