|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +CREATED AT: 2022年10月31日 |
| 4 | + |
| 5 | +URL: https://leetcode.com/problems/toeplitz-matrix/ |
| 6 | + |
| 7 | +GITHUB: https://github.com/Jiezhi/myleetcode |
| 8 | + |
| 9 | +FileName: 766-ToeplitzMatrix |
| 10 | + |
| 11 | +Difficulty: Easy |
| 12 | + |
| 13 | +Desc: |
| 14 | + |
| 15 | +Tag: |
| 16 | + |
| 17 | +See: |
| 18 | + |
| 19 | +""" |
| 20 | +from tool import * |
| 21 | + |
| 22 | + |
| 23 | +class Solution: |
| 24 | + def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: |
| 25 | + """ |
| 26 | + Runtime: 220 ms, faster than 18.00% |
| 27 | + Memory Usage: 14 MB, less than 36.74% |
| 28 | + |
| 29 | + m == matrix.length |
| 30 | + n == matrix[i].length |
| 31 | + 1 <= m, n <= 20 |
| 32 | + 0 <= matrix[i][j] <= 99 |
| 33 | + """ |
| 34 | + m, n = len(matrix), len(matrix[0]) |
| 35 | + |
| 36 | + def check(x, y) -> bool: |
| 37 | + while x < m - 1 and y < n - 1: |
| 38 | + x += 1 |
| 39 | + y += 1 |
| 40 | + if matrix[x][y] != matrix[x - 1][y - 1]: |
| 41 | + return False |
| 42 | + return True |
| 43 | + |
| 44 | + for i in range(m): |
| 45 | + if not check(i, 0): |
| 46 | + return False |
| 47 | + for i in range(1, n): |
| 48 | + if not check(0, i): |
| 49 | + return False |
| 50 | + return True |
| 51 | + |
| 52 | + |
| 53 | +def test(): |
| 54 | + assert Solution().isToeplitzMatrix(matrix=[[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]) |
| 55 | + assert not Solution().isToeplitzMatrix(matrix=[[1, 2], [2, 2]]) |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == '__main__': |
| 59 | + test() |
0 commit comments