Skip to content

Commit 5850f6d

Browse files
余杜林余杜林
authored andcommitted
添加0059.螺旋矩阵II Swift 版本
1 parent 4028047 commit 5850f6d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

problems/0059.螺旋矩阵II.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,61 @@ func generateMatrix(n int) [][]int {
302302
}
303303
```
304304

305+
Swift:
306+
307+
```swift
308+
func generateMatrix(_ n: Int) -> [[Int]] {
309+
var result = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)
310+
311+
var startRow = 0
312+
var startColumn = 0
313+
var loopCount = n / 2
314+
let mid = n / 2
315+
var count = 1
316+
var offset = 1
317+
var row: Int
318+
var column: Int
319+
320+
while loopCount > 0 {
321+
row = startRow
322+
column = startColumn
323+
324+
for c in column ..< startColumn + n - offset {
325+
result[startRow][c] = count
326+
count += 1
327+
column += 1
328+
}
329+
330+
for r in row ..< startRow + n - offset {
331+
result[r][column] = count
332+
count += 1
333+
row += 1
334+
}
335+
336+
for _ in startColumn ..< column {
337+
result[row][column] = count
338+
count += 1
339+
column -= 1
340+
}
341+
342+
for _ in startRow ..< row {
343+
result[row][column] = count
344+
count += 1
345+
row -= 1
346+
}
347+
348+
startRow += 1
349+
startColumn += 1
350+
offset += 2
351+
loopCount -= 1
352+
}
353+
354+
if (n % 2) != 0 {
355+
result[mid][mid] = count
356+
}
357+
return result
358+
}
359+
```
305360

306361

307362

0 commit comments

Comments
 (0)