-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0054.Spiral Matrix.swift
69 lines (53 loc) · 1.75 KB
/
0054.Spiral Matrix.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
62
63
64
65
66
67
68
69
class Solution {
private var matrix: [[Int]] = []
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
self.matrix = matrix
let rows = matrix.count
let cols = matrix[0].count
var result: [Int] = []
var minCol = 0, maxCol = cols-1
var minRow = 0, maxRow = rows-1
var itemsLeft = rows * cols
while itemsLeft > 0 {
var subRes = travel(true, minRow, minCol, maxCol)
result += subRes
itemsLeft -= subRes.count
minRow += 1
if itemsLeft <= 0 {
break
}
subRes = travel(false, maxCol, minRow, maxRow)
result += subRes
itemsLeft -= subRes.count
maxCol -= 1
if itemsLeft <= 0 {
break
}
subRes = travel(true, maxRow, maxCol, minCol)
result += subRes
itemsLeft -= subRes.count
maxRow -= 1
if itemsLeft <= 0 {
break
}
subRes = travel(false, minCol, maxRow, minRow)
result += subRes
itemsLeft -= subRes.count
minCol += 1
if itemsLeft <= 0 {
break
}
}
return result
}
private func travel(_ row: Bool, _ num: Int, _ from: Int, _ to: Int) -> [Int] {
var result: [Int] = []
result.reserveCapacity(abs(from - to) + 1)
let direction = from <= to ? 1 : -1
for i in stride(from: from, through: to, by: direction) {
let item = row ? matrix[num][i] : matrix[i][num]
result.append(item)
}
return result
}
}