-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathMedium_059_Spiral_Matrix_II.swift
61 lines (51 loc) · 1.26 KB
/
Medium_059_Spiral_Matrix_II.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
/*
https://leetcode.com/problems/spiral-matrix-ii/
#59 Spiral Matrix II
Level: medium
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Inspired by @yike at https://leetcode.com/discuss/21677/simple-c-solution-with-explaination
*/
import Foundation
struct Medium_059_Spiral_Matrix_II {
static func generateMatrix(_ n: Int) -> [[Int]] {
var res = Array<[Int]>(repeating: Array<Int>(repeating: 0, count: n), count: n)
var k = 1
var i = 0
while k <= n * n {
var j = i
while j < n - i {
res[i][j] = k
j += 1
k += 1
}
j = i + 1
while j < n - i {
res[j][n-i-1] = k
j += 1
k += 1
}
j = n - i - 2
while j > i {
res[n-i-1][j] = k
j -= 1
k += 1
}
j = n - i - 1
while j > i {
res[j][i] = k
j -= 1
k += 1
}
i += 1
}
return res
}
}