Es otra nueva semana. Vamos, hagámoslo.
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
if not matrix:
return True
if len(matrix)==1:
return True
#将行和列的元素都拿到
row = matrix[0]
col = [matrix[i][0] for i in range(len(matrix))]
row_size, col_size = len(matrix),len(matrix[0])
for i in range(len(row)):
tmp = row[i]
x,y =0,i
while x<row_size and y<col_size:
if tmp == matrix[x][y]:
x+=1
y+=1
else:
return False
for i in range(1,len(col)):
tmp = col[i]
x,y = i,0
while x<row_size and y<col_size:
if tmp == matrix[x][y]:
x+=1
y+=1
else:
return False
return True
row = len(matrix)
col = len(matrix[0])
for i in range(row):
for j in range(col):
if i>0 and j>0 and matrix[i][j]!=matrix[i-1][j-1]:
return False
return True
La llamada matriz de Toplitz significa que todos los elementos de la diagonal son todos iguales.
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
for i in range(len(matrix) - 1):
print(matrix[i][:-1],matrix[i + 1][1:])
if matrix[i][:-1] != matrix[i + 1][1:]:
return False
return True
Si no puede poner una fila o solo puede cargar una fila incompleta, use el método de corte para hacerlo. Debido a que los llamados elementos diagonales son todos iguales, significa que la línea anterior y la línea siguiente son diferentes en un elemento. Con este método, puede juzgar si los elementos diagonales son iguales.
Resumen: El método de corte es más inteligente que los métodos anteriores y el código es más conciso, es una muy buena idea para resolver el problema.