Given an m x n integer matrix matrix, return True if the matrix is Toeplitz. Otherwise, return False.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Function Signature
def is_toeplitz_matrix(matrix: list[list[int]]) -> bool:
Rules
-
matrix
is a list of rows, and every row has the same length
n
.
-
A diagonal is the set of cells
(i, j)
with the same value of
i - j
. A diagonal with one cell always satisfies the condition.
Constraints
-
m == len(matrix)
-
n == len(matrix[i])
-
1 <= m, n <= 20
-
0 <= matrix[i][j] <= 99
Examples
Input: matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output: True
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
| 5 | 1 | 2 | 3 |
+---+---+---+---+
| 9 | 5 | 1 | 2 |
+---+---+---+---+
The diagonals are [1, 1, 1], [2, 2, 2], [3, 3], [4], [5, 5] and [9]. Each holds a single value, so the matrix is Toeplitz.
Input: matrix = [[1, 2], [2, 2]]
Output: False
+---+---+
| 1 | 2 |
+---+---+
| 2 | 2 |
+---+---+
The main diagonal is [1, 2], which has two different elements, so the matrix is not Toeplitz.
Input: matrix = [[3], [8], [3]]
Output: True
With a single column, every diagonal has exactly one cell, so the condition holds even though the column itself varies.