11/07/2021

[LeetCode] 766. Toeplitz Matrix

 Problem : https://leetcode.com/problems/toeplitz-matrix/

No need to travel diagonally. Only need to check if number of one position equals to the number on its bottom-right position.


class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        
        ROW = len(matrix)
        COLUMN = len(matrix[0])
        
        for y in range(ROW-1):
            for x in range(COLUMN-1):
                if matrix[y][x] != matrix[y+1][x+1]:
                    return False
                
        return True

The one liner solution:


class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        ROW = len(matrix)
        COLUMN = len(matrix[0])
        
        return all(matrix[y][x] == matrix[y+1][x+1] for y in range(ROW-1) for x in range(COLUMN-1))

No comments:

Post a Comment