-
Notifications
You must be signed in to change notification settings - Fork 888
/
SpiralMatrix.swift
61 lines (53 loc) · 1.47 KB
/
SpiralMatrix.swift
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
/**
* Question Link: https://leetcode.com/problems/spiral-matrix/
* Primary idea: Use four index to get the right element during iteration
*
* Time Complexity: O(n^2), Space Complexity: O(1)
*/
class SpiralMatrix {
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
var res = [Int]()
guard matrix.count != 0 else {
return res
}
var startX = 0
var endX = matrix.count - 1
var startY = 0
var endY = matrix[0].count - 1
while true {
// top
for i in startY...endY {
res.append(matrix[startX][i])
}
startX += 1
if startX > endX {
break
}
// right
for i in startX...endX {
res.append(matrix[i][endY])
}
endY -= 1
if startY > endY {
break
}
// bottom
for i in stride(from: endY, through: startY, by: -1) {
res.append(matrix[endX][i])
}
endX -= 1
if startX > endX {
break
}
// left
for i in stride(from: endX, through: startX, by: -1) {
res.append(matrix[i][startY])
}
startY += 1
if startY > endY {
break
}
}
return res
}
}