[Leetcode] 766. Toeplitz Matrix

whitehousechef·2025년 10월 24일

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

initial

i was totally wrong. i was thinking to impl like first row check all the way until last row but this complicates this logic. Instead, we should just iter by row and compare the next row's values and not do like dfs (deep all the way). And in the first example i totally missed the 5-5 pair in the second and third row. So actually we should iter until row-2 and col-2 cuz its bottom right neighbour will be at row-1 or col-1 which is the boundary of the matrix.

sol

so iterating from first row, we check if theres bottom right neighbour that is same value (i.e. matrix[i][j]==matrix[i+1][j+1]

class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        row,col = len(matrix),len(matrix[0])
        for i in range(row-1):
            for j in range(col-1):
                if matrix[i][j]!=matrix[i+1][j+1]:
                    return False
        return True

complexity

nm time
1 space

0개의 댓글