LeetCode 766 Toeplitz Matrix 解题报告

题目要求

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.

题目分析及思路

给定一个M x N的矩阵,判断这个矩阵是不是Toeplitz。符合条件的矩阵应满足从左上到右下的每条对角线上的元素都相同。我们可以发现同一条对角线上的元素的行号与列号的差值是相同的,所以我们可以用一个字典将该差值存储为key,对应的value为元素值。

python代码

 

class Solution:

    def isToeplitzMatrix(self, matrix: 'List[List[int]]') -> 'bool':

        groups = {}

        for r, row in enumerate(matrix):

            for c, e in enumerate(row):

                if r-c not in groups:

                    groups[r-c] = e

                elif groups[r-c] != e:

                    return False

        return True

        

        

 

posted on 2019-02-21 09:32  锋上磬音  阅读(97)  评论(0编辑  收藏  举报