766. 托普利茨矩阵

# 这道题还是很简单的,判断对角线上边的数字相同就好了。
# 一次遍历,最左边从下到上遍历,最上边从左到右遍历。
from typing import List
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
# 求出列的长度和行的长度。
col,row = len(matrix),len(matrix[0])
# 其中有一个为零就代表着没有数字,返回真。
if col == 0 or row == 0:return True
for i in range(col - 1,-1,-1):
# 最左边从下到上遍历。
j = 0
# 判断对较线的数字是否都相同、
while 0 <= i + 1 < col and 0 <= j + 1 < row:
# 这里如果不相同的话直接函数返回假,就不用判断后边得了。
if matrix[i][j] != matrix[i + 1][j + 1]:
return False
i += 1
j += 1
# 同上。
for j in range(row):
i = 0
while 0 <= i + 1 < col and 0 <= j + 1 < row:
if matrix[i][j] != matrix[i + 1][j + 1]:
return False
i += 1
j += 1
# 中间过程都没有返回的话,那最后就返回真。
return True
A = Solution()
print(A.isToeplitzMatrix(matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]))
print(A.isToeplitzMatrix(matrix = [[1,2],[2,2]]))
原文地址:https://www.cnblogs.com/cong12586/p/14428616.html