算法——托普利茨矩阵

托普利茨矩阵

# ToeplitzMatrix 托普利茨矩阵
class Solution:
    def is_toeplitz_matrix(self, matrix):
        for i in range(len(matrix[0])):
            for v in range(1, len(matrix)):
                try:
                    if matrix[0][i] != matrix[v][i+v]:
                        return False
                except:
                    break
        for i in range(1, len(matrix)):
            count = 1
            for v in range(i+1, len(matrix)):
                try:
                    if matrix[i][0] != matrix[v][count]:
                        return False
                    count += 1
                except:
                    break
        return True

    def is_toeplitz_matrix_easy(self, matrix):
        # 更简单的做法
        n = len(matrix)  # rows
        m = len(matrix[0])  # cols
        for r in range(1, n):
            if matrix[r][1:] != matrix[r-1][:m-1]:
                return False
        return True



if __name__ == '__main__':
    matrix1 = [
        [1, 2, 3, 4],
        [5, 1, 2, 3],
        [9, 5, 1, 2]
    ]
    matrix2 = [
        [1, 2],
        [2, 2]
    ]
    matrix3 = [
        [41, 45],
        [81, 41],
        [73, 81],
        [47, 73],
        [0, 47],
        [79, 76]
    ]
    print(Solution().is_toeplitz_matrix(matrix1))
    print(Solution().is_toeplitz_matrix(matrix2))
    print(Solution().is_toeplitz_matrix(matrix3))

    print(Solution().is_toeplitz_matrix_easy(matrix1))
    print(Solution().is_toeplitz_matrix_easy(matrix2))
    print(Solution().is_toeplitz_matrix_easy(matrix3))    

 

上一篇:git开发流程、常用命令及工具、TortoiseGit使用及常见问题


下一篇:连连看beta发布