-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0766_toeplitz_matrix.py
More file actions
63 lines (59 loc) · 1.91 KB
/
0766_toeplitz_matrix.py
File metadata and controls
63 lines (59 loc) · 1.91 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
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
m = len(matrix)
n = len(matrix[0])
# Save the previous number
prev = -1
# Top to bottom, bottom to top
if (m <= n):
# Top to the bottom
for col in range(n):
prev = matrix[0][col]
i = 1
j = col + 1
while (i < m and j < n):
# Not Toeplitz
if (prev != matrix[i][j]):
return False
i += 1
j += 1
prev = -1
# Bottom to the top
for col in reversed(range(n)):
prev = matrix[m - 1][col]
i = m - 2
j = col - 1
while (i >= 0 and j >= 0):
# Not Toeplitz
if (prev != matrix[i][j]):
return False
i -= 1
j -= 1
prev = -1
# If m > n; Left to right, right to left
else:
# Left to the right
for row in range(m):
prev = matrix[row][0]
i = row + 1
j = 1
while (i < m and j < n):
# Not Toeplitz
if (prev != matrix[i][j]):
return False
i += 1
j += 1
prev = -1
# Right to the left
for row in reversed(range(m)):
prev = matrix[row][n - 1]
i = row - 1
j = n - 2
while (i >= 0 and j >= 0):
# Not Toeplitz
if (prev != matrix[i][j]):
return False
i -= 1
j -= 1
prev = -1
return True