Show problems as
Classic problem #1572EasyArrayMatrix

Matrix Diagonal Sum

Real-world version: Adding Up Both Diagonals of a Panel
Tracked in this browser only
Read Matrix Diagonal Sum on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A square panel panel has as many rows as columns. Add up the tiles along the diagonal running from the top-left corner to the bottom-right one, and the tiles along the diagonal running from the top-right corner to the bottom-left one. A tile lying on both diagonals is counted only once.

Return that total.

Examples

Example 1

Input
panel = [[1, 2], [3, 4]]
Output
10

On a two by two panel the two diagonals between them cover all four tiles.

Example 2

Input
panel = [[3, 1, 1], [1, 3, 1], [1, 1, 3]]
Output
11

The first diagonal holds the three 3 tiles for 9. The other adds the two corner 1 tiles, while the middle tile lies on both and is counted once.

Example 3

Input
panel = [[100, 1], [1, 100]]
Output
202

The two 100 tiles sit on the first diagonal and the two 1 tiles on the other.

Constraints

  • 1 <= panel.length <= 100
  • panel[i].length == panel.length
  • 1 <= panel[i][j] <= 100

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def diagonal_sum(panel: list[list[int]]) -> int:
Java
public int diagonalSum(int[][] panel)