-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0766_toeplitz_matrix.py
More file actions
92 lines (74 loc) · 2.2 KB
/
0766_toeplitz_matrix.py
File metadata and controls
92 lines (74 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#------------------------------------------------------------------------------
# Questions
#------------------------------------------------------------------------------
# tags:
'''
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.
Example 1:
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
Input:
matrix = [
[1,2],
[2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
class Solution:
'''
Time:
Space:
'''
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
R = len(matrix)
C = len(matrix[0])
def checkDiagonals(r,c):
'''returns true if diagnal is all the same number'''
num = matrix[r][c]
while r < R and c < C:
print(f'({r},{c}):{matrix[r][c]}')
if matrix[r][c] != num:
return False
r += 1
c += 1
return True
if all([checkDiagonals(0, c) for c in range(C)]) and \
all([checkDiagonals(r, 0) for r in range(1, R)]):
return True
return False
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
s = Solution()
self.assertEqual(s.isToeplitzMatrix(matrix), True)
def test_simple(self):
matrix = [[1,2,3,4]]
s = Solution()
self.assertEqual(s.isToeplitzMatrix(matrix), True)
unittest.main(verbosity=2)