-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0766_toeplitz_matrix.swift
More file actions
79 lines (75 loc) · 2.2 KB
/
0766_toeplitz_matrix.swift
File metadata and controls
79 lines (75 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
class Solution {
func isToeplitzMatrix(_ matrix: [[Int]]) -> Bool {
let m = matrix.count
let n = matrix[0].count
// Save the previous number
var prev = -1
// Top to bottom, bottom to top
if (m <= n) {
// Top to the bottom
for col in 0..<n {
prev = matrix[0][col]
var i = 1
var j = col + 1
while (i < m && j < n) {
// Not Toeplitz
if (prev != matrix[i][j]) {
return false
}
i += 1
j += 1
}
prev = -1
}
// Bottom to the top
for col in (0..<n).reversed() {
prev = matrix[m - 1][col]
var i = m - 2
var j = col - 1
while (i >= 0 && 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 0..<m {
prev = matrix[row][0]
var i = row + 1
var j = 1
while (i < m && j < n) {
// Not Toeplitz
if (prev != matrix[i][j]) {
return false
}
i += 1
j += 1
}
prev = -1
}
// Right to the left
for row in (0..<m).reversed() {
prev = matrix[row][n - 1]
var i = row - 1
var j = n - 2
while (i >= 0 && j >= 0) {
// Not Toeplitz
if (prev != matrix[i][j]) {
return false
}
i -= 1
j -= 1
}
prev = -1
}
}
return true
}
}