Feburary-766. Toplitz matrix

It's another new week, let's cheer on the bricks, cheer on the questions.

 

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

The so-called Toplitz matrix means that all elements on the diagonal are all equal.

 

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

If you can't put a line or only load an incomplete line, use the slice method to do it. Because the so-called diagonal elements are all equal, it means that the previous line and the next line are different by one element. By this method, it can be judged whether the diagonal elements are equal.

Summary: The slicing method is more clever than the above methods, and the code is more concise. It is a very good idea to solve the problem.

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/113930592