[LeetCode]#766. Toeplitz Matrix
Feb 8, 2021
Environment: Python 3.8
Key technique: for
Given an m x n
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.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Analysis:
- There is no need to check matrix[2][0] and matrix[0][3]
- Check matrix[i-1][j-1] is equal matrix[i][j] or not.
- If is equal, reture True, else return False.
Solution:
class Solution:
def isToeplitzMatrix(self, matrix):
for i in range(1,len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i-1][j-1]!=matrix[i][j]:
return False
return True
Submissions:
Reference:
https://leetcode.com/problems/toeplitz-matrix/discuss/1045481/Easy-python-solution